Given a sorted array of positive integers nums, and a positive integer n. Select any number from the interval [1, n] and add it to nums, so that any number in the interval [1, n] can be represented by the sum of certain numbers in nums. Please output the minimum number of digits that meet the above requirements.
Example 1:
Input: nums = [1,3], n = 6
Output: 1
Explanation:
According to the existing combination [1], [3], [1,3] in nums, 1, 3, 4 can be obtained.
Now if we add 2 to nums, the combination becomes: [1], [2], [3], [1,3], [2,3], [1,2,3].
The sum can represent the numbers 1, 2, 3, 4, 5, 6, which can cover all the numbers in the interval [1, 6].
So we need to add at least one number.
Example 2:
Input: nums = [1,5,10], n = 20
Output: 2
Explanation: We need to add [2, 4].
Example 3:
Input: nums = [1,2,2], n = 5
Output: 0
public int minPatches(int[] nums, int n) {
int patches = 0, i = 0;
long miss = 1;
while (miss <= n) {
if (i < nums.length && nums[i] <= miss)
miss += nums[i++];
else {
miss += miss;
patches++;
}
}
return patches;
}