Greedy Algorithms8 sections · 316 units
Open in Course

Patching Array - Implementation

The code

Here is the solution:

function minPatches(nums, n)
 patches := 0
 miss := 1
 i := 0
 while miss <= n
 if i < length(nums) and nums[i] <= miss then
 miss := miss + nums[i]
 i := i + 1
 else
 miss := miss + miss
 patches := patches + 1
 return patches

Time: O(m+logn)O(m + \log n) where mm is array length. Space: O(1)O(1).

Either use an existing number to extend range, or patch with missmiss to double the range. Doubling means O(logn)O(\log n) patches at most.