又是滑动窗口的应用
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> FindGreatestSumOfSubArray(vector<int>& array) {
std::vector<int> res;
// 最大和、滑动窗口以及最大长度的左右区间
int sum = 0, left = 0, right = 0, maxl = 0, maxr = 0;
// dp[i] 表示以下标i结尾的子数组的最大和
std::vector<int> dp(array.size(), 0);
if (array.empty()) {
return res;
}
sum = dp[0] = array[0];
for (int i = 1; i < array.size(); ++i) {
++right;
dp[i] = std::max(dp[i - 1] + array[i], array[i]);
// 更新区间
if (dp[i - 1] + array[i] < array[i]) {
left = right;
}
// 更新最大值
if (dp[i] > sum || dp[i] == sum && (right - left + 1) > (maxr - maxl + 1)) {
sum = dp[i];
maxl = left;
maxr = right;
}
}
for (int i = maxl; i <= maxr; ++i) {
res.push_back(array[i]);
}
return res;
}
};