Practice › Greedy
Patching an Array
Hard · Greedy · Asked at Google, Amazon
The array is sorted and positive. Add ("patch") as few numbers as possible so that every integer in [1, target] can be written as the sum of some elements of the array (each element used at most once). Print the minimum number of patches.
Input
First line: n target. Second line: the n sorted numbers (or an empty line when n = 0).
Output
The minimum number of patches.
Constraints
- 0 ≤ n ≤ 10^4
- 1 ≤ a[i] ≤ 10^4
- 1 ≤ target ≤ 2^31 − 1
Keep miss = the smallest sum not yet reachable (start at 1, everything in [1, miss) is reachable). If the next element is ≤ miss, use it: miss += a[i]. Otherwise patch the number miss itself, which doubles the reachable range. Stop when miss > target. miss can pass 2^31 — use 64-bit integers.
Example 1
Input
2 6 1 3
Output
1
Example 2
Input
3 20 1 5 10
Output
2
Example 3
Input
3 5 1 2 2
Output
0
Hints
- Suppose every sum in [1, miss) can already be formed.
- An element x ≤ miss extends that range to [1, miss + x).
- If the next element is bigger than miss, nothing can form miss — patch miss itself, which doubles the range.
Approach
Start with miss = 1. While miss ≤ target: if the next array element is ≤ miss, use it (miss += a[i], i++); otherwise add the patch miss (miss += miss, patches++). Adding miss is the best possible patch because it is the largest number that still keeps the range gap-free. Since miss at least doubles with every patch, there are only O(log target) patches. miss can exceed 2^31, so use 64-bit integers. Read all tokens — the second line may be empty when n = 0.
Complexity: O(n + log target) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long target;
cin >> n >> target;
vector<long long> a(n);
for (auto &x : a) cin >> x;
long long miss = 1;
int i = 0, patches = 0;
while (miss <= target) {
if (i < n && a[i] <= miss) miss += a[i++];
else {
miss += miss;
patches++;
}
}
cout << patches << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, target = data[0], data[1]
a = data[2 : 2 + n]
miss, i, patches = 1, 0, 0
while miss <= target:
if i < n and a[i] <= miss:
miss += a[i]
i += 1
else:
miss += miss
patches += 1
print(patches)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long target = (long) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
long miss = 1;
int i = 0, patches = 0;
while (miss <= target) {
if (i < n && a[i] <= miss) miss += a[i++];
else {
miss += miss;
patches++;
}
}
System.out.println(patches);
}
}