Problem 45
Minimum Size Subarray Sum
Medium · 20 pts · Array, Sliding Window, Binary Search
Problem
You are given an array of N positive integers and a target T. Find the length of the shortest block of consecutive elements whose sum is at least T. If even the whole array sums to less than T, print 0. Because all numbers are positive, a sliding window works: extend the window to the right, and whenever its sum reaches T, record its length and shrink it from the left as far as possible while the sum stays at least T. Each element enters and leaves the window once, so this is O(N).
Input
First line: integers N and T. Second line: N space-separated positive integers.
Output
Print the minimal length, or 0.
Constraints
1 <= N <= 100000; 1 <= A[i] <= 10000; 1 <= T <= 1000000000
Example input
6 7 2 3 1 2 4 3
Example output
2
Explanation
In 2 3 1 2 4 3 with T = 7, the window 4 3 has sum 7 and length 2. No single element reaches 7, so the shortest length is 2.