862. Shortest Subarray with Sum at Least K
Return the length of the shortest, non-empty, contiguous subarray ofAwith sum at leastK.
If there is no non-empty subarray with sum at leastK, return-1.
Example 1:
Input:
A = [1], K = 1
Output: 1Example 2:
Input:
A = [1,2], K = 4
Output: -1Example 3:
Input:
A = [2,-1,2], K = 3
Output: 3Note:
1 <= A.length <= 50000-10 ^ 5 <= A[i] <= 10 ^ 51 <= K <= 10 ^ 9
Thoughts:
Using Deque + keeping increasing order: only larger index in the queue can have larger sum value. We use cumulative sum and priority queue that maintains minimal value within the window of a given length. We then iterate over all possible ends of windows and check, what is the maximal possible sum across all windows of length l <= L that end at this element.
Segment Tree:
TreeMap.submap
Binary Search
https://buptwc.github.io/2018/07/02/Leetcode-862-Shortest-Subarray-with-Sum-at-Least-K/
Code: Deque. O(n)
Code: Python
Code: Java
Code: Segment Tree:
Code: Java subMap
Code: Java Binary Search
Last updated
Was this helpful?