LeetCode: Shortest Subarray with Sum at Least K Posted on August 5, 2019July 26, 2020 by braindenny Shortest Subarray with Sum at Least K Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #maxsubarraysum, #monotone Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, 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 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9 Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: monotone queue // https://code.dennyzhang.com/shortest-subarray-with-sum-at-least-k // Basic Ideas: presum + monotone queue // // Get a presum array // If current value is smaller than previous value, // for the following values, // no need to compare with previous values any more // // Complexity: Time O(n), Space O(n) func shortestSubarray(A []int, K int) int { presums := make([]int, len(A)+1) for i, v := range A { presums[i+1] = presums[i] + v } res := 1<<31-1 // find next +K greater value // items in queue are increassing queue := []int{} for i, v := range presums { // previous value can't be candidates for len(queue)>0 && v <= presums[queue[len(queue)-1]] { // remove the item queue = queue[0:len(queue)-1] } // find candidates for len(queue)>0 && presums[queue[0]] + K <= v { j := queue[0] queue = queue[1:] if i-j < res { res = i-j } } // put current element to be evaluated queue = append(queue, i) } if res == 1<<31-1{ res = -1 } return res } Post Views: 0