标签:cto etc pre subarray sub int 最大 向量 span
思路:
分治法。记最大子序和为maxResult,函数为int getMaxSub( *, * ) {}。
向量A= [a1, a2, a3, ...., ai, ai+1, a+2, ......, aj-1, aj],
maxResult = max( maxresult(a1, ......, ai), getMaxSub(*, i+1) ),其中sum(a1, ......, ai) <= 0.
class Solution { public: int maxSubArray(vector<int>& nums) { if(nums.size() == 0) return -1; return getMaxSub(nums, 0); } int getMaxSub(const vector<int>& vecInt, int index) { int maxR = vecInt[index], sum = 0; for(index; index < vecInt.size(); ++index) { sum = sum + vecInt[index]; if(sum <= 0 && index < (vecInt.size() - 1)) { // 确保下一级序列非空 maxR = max(maxR, getMaxSub(vecInt, index+1)); return maxR; } else { maxR = max(maxR, sum); } } return maxR; } };
标签:cto etc pre subarray sub int 最大 向量 span
原文地址:https://www.cnblogs.com/gdut-gordon/p/11491420.html