Patching Array - Problem
Given a sorted integer array nums and an integer n, you need to 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.
The patching strategy should ensure that we can represent all integers from 1 to n using subsets of the modified array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3], n = 6
›
Output:
1
💡 Note:
We can make [1,3,4] with the array. Missing 2,5,6. By patching 2, we can make [1,2,3,4,5,6]. Only 1 patch needed.
Example 2 — Empty Array
$
Input:
nums = [1,5,10], n = 20
›
Output:
2
💡 Note:
With [1,5,10], we can make some sums but need patches. We need to patch 2 and 4 to cover [1,20].
Example 3 — No Patches Needed
$
Input:
nums = [1,2,2], n = 5
›
Output:
0
💡 Note:
We can make [1,2,3,4,5] using subsets: 1→[1], 2→[2], 1+2→[3], 2+2→[4], 1+2+2→[5]. No patches needed.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 104
- nums is sorted in ascending order
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code