|
| 1 | +# Time: O(s + logn), s is the number of elements in the array |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# Given a sorted positive integer array nums and |
| 5 | +# an integer n, add/patch elements to the array |
| 6 | +# such that any number in range [1, n] inclusive |
| 7 | +# can be formed by the sum of some elements in the |
| 8 | +# array. Return the minimum number of patches required. |
| 9 | +# |
| 10 | +# Example 1: |
| 11 | +# nums = [1, 3], n = 6 |
| 12 | +# Return 1. |
| 13 | +# |
| 14 | +# Combinations of nums are [1], [3], [1,3], which form |
| 15 | +# possible sums of: 1, 3, 4. |
| 16 | +# Now if we add/patch 2 to nums, the combinations are: |
| 17 | +# [1], [2], [3], [1,3], [2,3], [1,2,3]. |
| 18 | +# Possible sums are 1, 2, 3, 4, 5, 6, which now covers |
| 19 | +# the range [1, 6]. |
| 20 | +# So we only need 1 patch. |
| 21 | +# |
| 22 | +# Example 2: |
| 23 | +# nums = [1, 5, 10], n = 20 |
| 24 | +# Return 2. |
| 25 | +# The two patches can be [2, 4]. |
| 26 | +# |
| 27 | +# Example 3: |
| 28 | +# nums = [1, 2, 2], n = 5 |
| 29 | +# Return 0. |
| 30 | + |
| 31 | + |
| 32 | +class Solution(object): |
| 33 | + def minPatches(self, nums, n): |
| 34 | + """ |
| 35 | + :type nums: List[int] |
| 36 | + :type n: int |
| 37 | + :rtype: int |
| 38 | + """ |
| 39 | + patch, miss, i = 0, 1, 0 |
| 40 | + while miss <= n: |
| 41 | + if i < len(nums) and nums[i] <= miss: |
| 42 | + miss += nums[i] |
| 43 | + i += 1 |
| 44 | + else: |
| 45 | + miss += miss |
| 46 | + patch += 1 |
| 47 | + |
| 48 | + return patch |
0 commit comments