動機
有點魔法的一題
Problem
Given a sorted integer array nums
and an integer n
, add/patch elements to the array such that any number in the 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:
Input: nums = [1,3], n = 6Output: 1Explanation: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:
Input: nums = [1,5,10], n = 20Output: 2Explanation: The two patches can be [2, 4].
Example 3:
Input: nums = [1,2,2], n = 5Output: 0
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 104
nums
is sorted in ascending order.1 <= n <= 231 - 1
Sol
假設現在可以組合出的數字是1~miss
,所以有兩個case
如果目前的數字在可以組合出的範圍中,就直接加上去
如果不在,就是加最大的數字,miss
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
miss = 1
i = 0
ret = 0
while miss <= n:
if i < len(nums) and nums[i] <= miss:
miss += nums[i]
i += 1
else:
miss += miss
ret += 1
return ret