Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Patching Array

Cover all sums

Given a sorted array and a target nn, find the minimum number of patches (additions) needed so that any number in [1,n][1, n] can be formed as a sum of some elements. For nums=[1,3]nums = [1,3], n=6n = 6: you can make {1,3,4}\{1, 3, 4\} but not 22, 55, 66. Add 22 to make all of [1,6][1, 6]. Answer is 11.

Think about what range of sums you can currently make, and what happens when you add a new number. Tricky: the array is sorted, which lets you process numbers in increasing order.

If you can make [1,5][1, 5] and the next number is 77, you cannot make 66. Adding 66 extends the range to [1,11][1, 11] because you can now combine 66 with existing sums.