[LeetCode] Patching Array
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]Specified sive 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.
Solutions
Suppose the range that the array can currently represent is[1, total)To add elements to the array.addExtend the representation range[1, total + add), Whereadd≤total. When and only whenadd=totalMaximum time range[1, 2 * total).
When the array contains less than or equal
addThe elements in the array are used. If no, add a new element.
add. Implementation Code
//Runtime: 1 mspublic class Solution { public int minPatches(int[] nums, int n) { long miss = 1; int add = 0; int i = 0; while (miss <= n) { if (i < nums.length && nums[i] <= miss){ miss += nums[i++]; } else { miss += miss; add += 1; } } return add; }}