Microsoft OA 面试真题解析:Minimum Number of Coins to Make All Sums in Range

16次阅读
没有评论

You are given a 0-indexed integer array coins, representing the values of the coins available, and an integer target.

An integer x is obtainable if there exists a subsequence of coins that sums to x.

Return the minimum number of coins of any value that need to be added to the array so that every integer in the range [1, target] is obtainable.

A subsequence of an array is a new non-empty array formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.

Example

Input: coins = [1,4,10], target = 19
Output: 2
Explanation: We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added.

这道题的核心是贪心维护“当前已经可以表示到的连续区间”。设我们已经能覆盖到区间 [1, reach],那么如果下一个硬币面值 coins[i] 不超过 reach + 1,就可以把可覆盖范围扩展到 reach + coins[i];否则就必须补一个面值为 reach + 1 的硬币,这样扩展速度最快,且能把缺口一次补上。重复这个过程,直到可覆盖范围达到 target。题目本质上是经典的 patching array / 最少补数问题,通常先排序 coins,再线性扫描即可,时间复杂度为 O(n log n)(排序)加 O(n) 扫描,空间复杂度 O(1) 或 O(log n) 取决于排序实现。

正文完
 0