Sponsored
Sponsored
This approach uses a greedy strategy to find the minimum number of patches required to cover the entire range [1, n]. Starting with a number missing
initialized to 1, which represents the smallest sum we cannot form, we iterate through the array. If the current number in the array is less than or equal to missing
, we increment our range to missing + nums[i]
. Otherwise, we add missing
to the array, effectively patching it, and increment our missing
sum by itself.
Time complexity: O(m + log n) where m is the length of nums
. The loop runs through nums
and potentially adds new numbers until missing
> n
.
Space complexity: O(1), since no auxiliary space is used apart from a few variables.
1class Solution:
2 def minPatches(self, nums, n):
3 patches, i, missing = 0, 0, 1
4 while missing <= n:
5 if i < len(nums) and nums[i] <= missing:
6 missing += nums[i]
7 i += 1
8 else:
9 missing += missing
10 patches += 1
11 return patches
12
13# Example usage
14solution = Solution()
15result = solution.minPatches([1, 3], 6)
16print(result) # Output: 1
The Python solution is easy to read and concise. By iterating through the sorted list of numbers, it keeps a running tally of the smallest missing
sum and applies patches when necessary to ensure full coverage up to n.