Daily Archives: January 29, 2016

Patching Array

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:
nums = [1, 3], n = 6
Return 1.

Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].

Example 3:
nums = [1, 2, 2], n = 5
Return 0.

Solution. The idea is that suppose by adding some elements, we can get the sum s. And if there is an element e less than s that we haven’t used. Then we can get reach [1,…, s+e].

For example, 1, 2, 3, 4, 8. By summing 1+2+3+4, we know it can reach [1,…,10]:
[1], [2], [3], [4], [1 + 4], [2 + 4], [3 + 4], [1 + 3 + 4], [1 + 2 + 3 + 4]

The next one is 8 which is less than sum 10. Then by adding 10 + 8 = 18, we know that it can get reach [1,…,18].

Let’s go back to the problem. Take [1, 4, 10], n = 20 for example. It can reach 1 by [1]. And it can’t reach 2. So we put 2 in array.

1 + 2 = 3. We know it can reach 3. Now 3 is the furthest it can reach.

Next element is 4, so we can reach 4. 3 + 4 = 7, we know by now, it can reach 7.

Then next element is 10. 7 can’t reach it. So we put 8 after 7, 7 + 8 = 15. We know it can reach 15.

By now, we can’t reach 20 yet. So we put 16, we have 16 + 15 = 31.

By total, we put 3 numbers.

Explanation is a bit complex. Original solution is from here.

Check my code on github: link