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: 1

Example 2:

Input: 
A = [1,2], K = 4
Output: -1

Example 3:

Input: 
A = [2,-1,2], K = 3
Output: 3

Note:

  1. 1 <= A.length <= 50000

  2. -10 ^ 5 <= A[i] <= 10 ^ 5

  3. 1 <= K <= 10 ^ 9

Thoughts:

  1. 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.

  2. Segment Tree:

  3. TreeMap.submap

  4. Binary Search

https://buptwc.github.io/2018/07/02/Leetcode-862-Shortest-Subarray-with-Sum-at-Least-K/

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143726/C++JavaPython-O(N)-Using-Deque

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/151169/my-solution-O(nlgn)-use-segment-tree

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/144291/Java-TreeMap.submap-Solution

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143828/Java-binary-search-O(NlogN\

Code: Deque. O(n)

Code: Python

Code: Java

Code: Segment Tree:

Code: Java subMap

Code: Java Binary Search

Last updated

Was this helpful?