All problems

Problem 215

Shortest Subarray with Sum at Least K

Hard · 30 pts · Array, Prefix Sum, Monotonic Queue, Sliding Window

Problem

You are given an array of N integers, which may be negative, and a positive number K. Find the length of the shortest non-empty block of consecutive elements whose sum is at least K, or print -1 if no block reaches K. Because of negative numbers, a simple sliding window fails. Use prefix sums and a deque of indices with increasing prefix sums: for each new prefix sum, pop from the front while it is at least K more than the front's (recording the length), and pop from the back any index with a prefix sum not smaller than the new one.

Input

First line: integers N and K. Second line: N space-separated integers.

Output

Print the minimum length, or -1.

Constraints

1 <= N <= 100000; -100000 <= A[i] <= 100000; 1 <= K <= 1000000000

Example input

3 3
2 -1 2

Example output

3

Explanation

In 2 -1 2 with K = 3, no single element or pair reaches 3 (the pairs sum to 1). The whole array sums to 2 - 1 + 2 = 3, so the shortest length is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Range Increment Updates Next: Count Words