Leetcode 862 shorest subarray with sum at least K

Source: Internet
Author: User

Https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/

 

First, reviewValueThe method is to record a prefix min value and then scan the sum array.

 

1. First, we don't need the maximum value here, because it's just enough K.

2. The shortest distance is required. Is the shortest length of the array.

 

The idea here is the same, but it is better to save a lot of Min values, that is, to use a queue to save the min value of the prefix without the min value.

That is, if the value of the sum array is:

... 60, 40... y .....

In the original queue, 60 can pop out, because it is replaced by 40, because the value of Y minus 40 must be greater than 60, and it is more likely to be greater than K, and the distance is shorter.

class Solution {public:    int shortestSubarray(vector<int> A, int k) {        int len = (int)A.size();        deque<int> que;        vector<int> sum(len + 1, 0);        for (int i = 0; i < len; ++i) {            sum[i + 1] = sum[i] + A[i];        }        int ans = len + 1;        que.push_back(0);        for (int i = 1; i <= len; ++i) {            while (que.size() > 0 && sum[i] - sum[que.front()] >= k) {                ans = min(ans, i - que.front());                que.pop_front();            }            while (que.size() > 0 && sum[i] <= que.back()) {                que.pop_back();            }            que.push_back(i);        }        return ans == len + 1 ? -1 : ans;    }} t;

 

Leetcode 862 shorest subarray with sum at least K

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.