Minimum Size Subarray Sum

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;
	}
};
posted @ 2015-09-10 03:01  影湛  阅读(122)  评论(0编辑  收藏  举报