CP: The shortest segment with enough sum

You have a list of positive whole numbers and a number S. Find the length of the shortest stretch of consecutive numbers whose sum is at least S.

What to build

Move the right end forward one number at a time, adding it to the window sum. While the sum is at least S, record the window length and then remove the left number and move the left end forward.

Requirements

  • Use a window that grows and shrinks, in O(n)
  • Print 0 if no stretch reaches S

Input

The first line has n and S. The second line has n positive numbers.

Output

The shortest length, or 0 if there is none.

Constraints

1 ≤ n ≤ 200,000. Numbers are from 1 to 10⁹. 1 ≤ S ≤ 10¹⁴.

Example

Input:

6 7
2 3 1 2 4 3

Output:

2

Why it works

Because every number is positive, adding on the right only raises the sum and removing on the left only lowers it. Once the window reaches S, removing from the left finds shorter windows ending at the same place, and the left end never has to go back. Each end moves at most n times.

Examples

Example 1 · Input
6 7
2 3 1 2 4 3
Expected output
2
Example 2 · Input
3 100
1 2 3
Expected output
0

Hints

Hint 1

Keep l = 0 and sum = 0. For r in 0..n-1: sum += a[r].

Hint 2

while (sum >= S): best = min(best, r - l + 1); sum -= a[l]; l++.

Hint 3

Start best at n + 1 and print 0 if it is still n + 1 at the end.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long S;
    cin >> n >> S;
    vector<long long> a(n);
    for (auto& x : a) cin >> x;
    int best = n + 1, l = 0;
    long long sum = 0;
    for (int r = 0; r < n; r++) {
        sum += a[r];
        while (sum >= S) {
            if (r - l + 1 < best) best = r - l + 1;
            sum -= a[l];
            l++;
        }
    }
    cout << (best == n + 1 ? 0 : best) << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Two pointers and sliding windows →