Skip to content
BytePatterns

Shortest Run Summing to at Least K

HardStacks & Queues#monotonic-deque#prefix-sum~40m

Problem

Given a list of integers nums, which may include negative numbers, and a positive integer k, return the length of the shortest non-empty contiguous run whose sum is at least k. If no run reaches k, return -1.

Examples

Input:  nums = [2, -1, 2], k = 3
Output: 3
Why:    only the whole list sums to 3
Input:  nums = [84, -37, 32, 40, 95], k = 167
Output: 3
Why:    32 + 40 + 95 = 167; the whole list sums to 214 but is longer
Input:  nums = [1, 2], k = 4
Output: -1
Why:    edge case, even the whole list falls short

Hints

0 / 3

Stuck on the idea rather than the code? Sliding Window Maximum covers it.