Patching Array
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that a NY number in range [1, n]
inclusive can is 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 [1], [3], [1,3]
is, which form possible sums of: 1, 3, 4
.
Now if we add/patch 2
to nums, the combinations is: [1], [2], [3], [1,3], [2,3], [1,2,3]
.
Possible sums 1, 2, 3, 4, 5, 6
is, which now covers the range [1, 6]
.
So we are only need 1
patch.
Example 2:
nums = [1, 5, 10]
, n =20
Return 2
.
The both patches can be [2, 4]
.
Example 3:
nums = [1, 2, 2]
, n =5
Return 0
.
https://leetcode.com/problems/patching-array/
Combine the numbers in the Nums array to fill the range of [1, n], and if you have an empty combination number, you need to patch into the nums array for a minimum of a few patches.
Https://leetcode.com/discuss/82822/solution-explanation
Greedy, from small to large fill [1, n], can use the original nums in the number of time to use off, not enough to patch.
For example, nums = [1, 5, ten], n = 40.
The first is missing 2,patch 2, when the range is [1, 3], that is, 1∪2∪1 + 2.
This side also uses less than 5,patch 4, when the range is [1, 7], that is [1, 3]∪4∪[1 + 4, 3 + 4].
5 in the range of [1, 7] can be used 5, this time the range is [1, 12], that is [1, 7]∪[1 + 5, 7 + 5].
10 in the range of [1, 12], with 10, this range is [1, 22], i.e. [1, 12]∪[1 + 10, 12 + 10].
Patch 23, at which time the range is [1, 45], i.e. [1, 22]∪23∪[1 + 23, 22 + 23].
Finally, 3 patch[2, 4, 23] are required.
Code according to this idea, first look at the number of nums can be used, if not, add a patch.
1 /**2 * @param {number[]} nums3 * @param {number} n4 * @return {number}5 */6 varMinpatches =function(Nums, n) {7 varCountpatch = 0, Numsindex = 0;8 for(vari = 1; I <=N;) {9 if(Nums[numsindex] <i) {Teni + =Nums[numsindex]; Onenumsindex++; A Continue; - } - if(Nums[numsindex] = = =i) thenumsindex++; - Else -countpatch++; - if(I-1 > 0) +i + = I-1; -i++; + } A returnCountpatch; at};
[Leetcode] [JavaScript] Patching Array