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.
贪心算法,每次算出能到达的最大的值max,如果能到达比nums[i]小1的值,这就保证了1到nums[i]-1都能得到,故1到nums[i]+max都能取得,就能更新max值和使i+1.如果max比nums[i]-1小,说明还不能到达nums[j],则先加上比max大1的数(补上这个数),更新max.需要注意的是,如果i超过了nums数的个数,也是每次更新max使其加上比它大1的数.
代码:
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long long max=0;
int count=0,len=nums.size();
for(int i=0;max<n;)
{
if(i>=len||max<nums[i]-1)
{
max+=max+1;
count++;
}
else
{
max+=nums[i++];
}
}
return count;
}
};