题解 | #牛群喂食计划#
牛群喂食计划
https://www.nowcoder.com/practice/7da784c2befa4c2aaef46e2e37c23aee
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型vector * @param k int整型 * @return int整型 */ int numOfFeedPlans(vector<int>& nums, int k) { int beg, end, sum; beg = end = 0; sum = nums[0]; int n = nums.size(); int ans = 0; while (end < n) { if (sum == k) { ans++; while(end<n-1&&nums[end+1]==0) { ans++; end++; } sum -= nums[beg]; beg++; if (beg > end) { end = beg; sum = nums[beg]; continue; } while(end>beg&&nums[end]==0) { end--; } } if (sum > k) { sum -= nums[beg]; beg++; if (beg > end) { end = beg; sum = nums[beg]; continue; } } if(sum<k) { sum+=nums[++end]; } } return ans; } };