Greedy Algorithms8 sections · 316 units
Open in Course

Patching Array - The Idea

Extend the range

If you can make all sums in [1,miss1][1, miss-1], and you add a number xmissx \leq miss, you can now make all sums in [1,miss+x1][1, miss + x - 1]. Why? You already have [1,miss1][1, miss-1].

Adding xx gives you [x,miss1+x][x, miss-1+x]. Since xmissx \leq miss, these ranges overlap and combine to [1,miss1+x][1, miss-1+x]. The greedy choice: if missmiss is not covered, add missmiss itself.

It doubles your range because before you have [1,miss1][1, miss-1], after you get [1,2miss1][1, 2 \cdot miss - 1]. These ranges are consecutive because missmiss is the first missing number, so no gap exists.