lc 330. patching array

Description

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.

Input: nums = [1,3], n = 6

Output: 1

Explanation:

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.

Solution

We can use dp to handle it. miss means the minimum number we can not get at present (we can get all of the numbers smaller than miss).

If miss >= nums[i], we can update miss by miss + nums[i] as we can add nums[i] to all of the numbers we can get before.

If miss < nums[i] or i == len(nums), we can not get larger miss without patching, therefore, we should add miss to the array, thus we can
cover all of the numbers in [1, miss 2 - 1], so the current miss should be 2 miss.

1
2
3
4
5
6
7
8
9
class :
def minPatches(self, nums: List[int], n: int) -> int:
miss, add, i = 1, 0, 0
while miss <= n:
if i < len(nums) and miss >= nums[i]:
miss, i = miss + nums[i], i + 1
else:
miss, add = miss * 2, add + 1
return add