Minimum Size Subarray Sum

mac2022-06-30  23

Description:

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

For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

Solution:

class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { auto sz = (int)nums.size(); if (sz == 0) return 0; int rc = 0; int pre = 0; int sum = 0; int pos = 0; while (pos < sz) { sum += nums[pos]; if (sum < s) { ++pos; } else if (sum == s) { rc = (rc == 0) ? pos-pre+1 : min(rc, pos-pre+1); sum -= nums[pre]; ++pre; ++pos; } else { rc = (rc == 0) ? pos-pre+1 : min(rc, pos-pre+1); sum = sum - nums[pre] - nums[pos]; ++pre; } } return rc; } };

转载于:https://www.cnblogs.com/deofly/p/minimum-size-subarray-sum.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)