Shortest Subarray with Sum at Least K

hard queue prefix-sums sliding-window arrays 1000 ms · 256 MB

Shortest Subarray with Sum at Least K

You are given an array of n integers a_1, a_2, …, a_n (they may be negative or zero) and a number K.

Find the length of the shortest non-empty contiguous subarray a_l, a_{l+1}, …, a_r whose sum is at least K. If no such subarray exists, report that.

Input

The first line contains two integers n and K (1 ≤ n ≤ 10^6, 1 ≤ K ≤ 10^11).

The second line contains n integers a_1, a_2, …, a_n (−10^5 ≤ a_i ≤ 10^5).

Output

Print a single integer: the minimum value of r − l + 1 over all pairs 1 ≤ l ≤ r ≤ n with a_l + a_{l+1} + … + a_r ≥ K, or -1 if there is no such pair.

Notes

In the first example, the subarray 4 -1 5 has sum 8 ≥ 6, and no subarray of length 1 or 2 reaches 6.

In the second example, the largest possible subarray sum is 4, so the answer is -1.

Sums of subarrays can exceed the range of a 32-bit integer.

Example 1

Input

5 6
1 -3 4 -1 5

Output

3

Example 2

Input

3 5
-1 2 2

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

Work with prefix sums: a subarray is a difference of two prefix sums, and you want the closest pair with a large enough difference. Why does a plain two-pointer window fail when values can be negative?

Hint 2

For a fixed right end, when is a candidate left end never worth keeping? If an earlier left end has a prefix sum that is at least as large as a later one, what does that say about it? And once a left end has produced an answer, can it help any later right end?

Hint 3

Keep the useful left ends in a monotonic deque ordered by prefix sum, discarding candidates at both ends as the observations above allow. If each index enters and leaves only once, the scan is linear.

report an issue Prefer your own editor? sooks prep 35 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.