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
Patching Array - Greedy Approach INPUT Sorted Array: nums 1 3 idx: 0 idx: 1 Target Range: [1, n] n = 6 Need to form: 1,2,3,4,5,6 1 2 3 4 5 6 nums=[1,3], n=6 ALGORITHM STEPS 1 Initialize miss=1, patches=0 2 Check nums[0]=1 1 <= miss, use it miss = 1+1 = 2 3 miss=2, nums[1]=3 3 > 2, need patch! Add 2, patches=1 miss = 2+2 = 4 4 Use nums[1]=3 3 <= 4, use it miss = 4+3 = 7 5 Check: miss > n? 7 > 6, Done! Reachable: [1,6] OK With patch: 2 FINAL RESULT Patched Array: 1 2 ADDED 3 Achievable Sums: 1 2 3 4 5 6 1=1, 2=2, 3=3, 1+3=4 2+3=5, 1+2+3=6 OUTPUT 1 Minimum patches: 1 Key Insight: If we can form [1, miss-1], and nums[i] <= miss, we can extend to [1, miss+nums[i]-1]. If nums[i] > miss, we must patch by adding miss itself, doubling our reachable range! TutorialsPoint - Patching Array | Greedy - Track Maximum Achievable Sum
Asked in
Google 15 Amazon 8 Facebook 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen