1. 題目描述
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
2. 思路
- 用max_bound當前數組中的數可以表示[1, max_bound)
- 當遍歷數組下一個數時
- 如果num[i] <= max_bound, 那麼num[i] 可以由前面的數字表示出來, 即不會有斷層,結合這個新的數,我們可以表示連續的[1, max_bound + num[i])
- 如果 num[i] > max_bound, 那麼[max_bound, num[i])之間的數字就無法表示出來了, 所以我們需要插入一個數字,來防止這種不連續性,當我們添加的數字爲max_bound時,可以保證新的覆蓋範圍最大,即爲[1, max_bound * 2)
- 遍歷完整個數組或者max_bound > n 時停止。
3. 代碼
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int cnt = 0, i = 0;
long max_bound = 1;
while (max_bound <= n) {
if (i < nums.size() && max_bound >= nums[i]) {
max_bound += nums[i++];
} else {
max_bound *= 2;
++cnt;
}
}
return cnt;
}
};