class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param trees int整型vector
* @param M int整型
* @return int整型
*/
int maxFruits(vector<int>& trees, int M) {
// write code here
// 找子数组,子数组元素之和还要尽可能大,同时不超过 M
// 双指针法,定义滑动窗口的 start 和 end
int maxF = 0;
int currentSum = 0;
int start = 0;
for (int end = 0; end < trees.size(); ++end) {
currentSum += trees[end];
// 当前和超过 M 时,start 向 end 靠近,缩小窗口
while (currentSum > M) {
currentSum -= trees[start];
start++;
}
// 记录可能的最大果实收集数量
maxF = max(maxF, currentSum);
}
return maxF;
}
};