Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int res = INT_MAX, n = nums.size(); vector<int> p{0}; for(int l = 0, r = 0; r < n; r++) { p.push_back(p.back() + nums[r]); while(l <= r and p[r+1] - p[l] >= target) { res = min(res, r + 1 - l++); } } return res == INT_MAX ? 0 : res; } };