题解 | #连续子数组的最大和(二)#
连续子数组的最大和(二)
https://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21
#include <algorithm> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param array int整型vector * @return int整型vector */ vector<int> FindGreatestSumOfSubArray(vector<int>& array) { int sum = 0, max = array[0]; int l = 0, retl = 0, retr = 0; for(int i = 0; i < array.size(); i++) { if(sum < 0) { sum = array[i]; l = i; } else sum += array[i]; if(max < sum || (max == sum && (retr - retl < i - l))) { max = sum; retl = l; retr = i; } } vector<int> ret(array.begin() + retl, array.begin() + retr + 1); return ret; } };