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
.
题目大意:给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n]
区间内选取任意个数字补充到 nums 中,使得 [1, n]
区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。
思路: 贪心策略
维护一个当前序列所能得到的最大值max,最开始为0,遍历数组
判断当前值cur是否小于等于max+1,如果是,max+=cur,数组指针往后移动一位.
如果当前值大于max+1,则需要向数组中添加max+1,更新max所能达到的距离为2*max+1.数组指针不变
重复以上过程直到m>=n.
Code:
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int i=0,count=0;
long long maxnum = 0;
int len=nums.size();
while(maxnum<n)
{
if(i<len&&nums[i]<=maxnum+1)
{
maxnum+=nums[i];
i++;
}
else{
// cout<<count<<' ' <<maxnum<<endl;
maxnum+=(maxnum+1);
count++;
}
}
return count;
}
};