Leetcode 209. Minimum Size Subarray Sum和大于sum的最少子序列

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

题目链接:https://leetcode.com/problems/minimum-size-subarray-sum/

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
         int l = 0, r = 0, n = nums.size(), sum = 0, len = INT_MAX;
        while (r < n) 
        {
            sum += nums[r++];
            while (sum >= s) 
            {
                len = min(len, r - l);
                sum -= nums[l++];
            }
        }
        return len == INT_MAX ? 0 : len;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/88616342
今日推荐