Challenge: Shortest Stretch Reaching a Target
Completed
Read positive numbers and a target. Print the length of the shortest stretch of neighbouring numbers whose total is at least the target, or 0 if none.
Input
Line 1: n target. Line 2: n positive whole numbers.
Output
One number.
Example
Input
6 7 2 3 1 2 4 3
Output
2
Editor
C++
Hints
Grow the window with v[right].
While the total is big enough, record the length and shrink from the left.
Solution explanation
The window only moves forward: O(n).
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
long long target;
cin >> n >> target;
vector<long long> v(n);
for (auto& x : v) cin >> x;
int left = 0, best = 0;
long long total = 0;
for (int right = 0; right < n; right++) {
total += v[right];
while (total >= target) {
if (best == 0 || right - left + 1 < best) best = right - left + 1;
total -= v[left++];
}
}
cout << best << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module