标签:UI bsp and patch required amp array sorted ted
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
1 public class Solution { 2 public int MinPatches(int[] nums, int n) { 3 4 int i = 0, patches = 0; 5 long max = 1; 6 7 while (max <= n) 8 { 9 if (i < nums.Length && nums[i] <= max) 10 { 11 max += nums[i]; 12 i++; 13 } 14 else 15 { 16 max += max; 17 patches++; 18 } 19 } 20 21 22 return patches; 23 } 24 }
标签:UI bsp and patch required amp array sorted ted
原文地址:http://www.cnblogs.com/liangmou/p/8016088.html