Leetcode 330: Patching Array

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 330: 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]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 }

 










以上是关于Leetcode 330: Patching Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-330.Patching Array

330. Patching Array

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java