Problem:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
Solution:
最直接的想法就是计算每个子数组的和,然后求出最大值,但复杂度是O(n^3). 还有就是遍历数组,用变量记录加上下一个元素后的值,与之前计算出的最大值比较。当计算出的和小于0时,继续扩展这个子数组得到的和肯定小于重新开始计算一个子数组的值,所以记录值归零,代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = nums[0], tmpSum = 0;
for (int index = 0; index < nums.size(); ++index){
tmpSum += nums[index];
maxSum = max(maxSum, tmpSum);
if (tmpSum < 0)
tmpSum = 0;
}
return maxSum;
}
};
上述解法复杂度为O(n), LeetCode上测试的运行时间为12 ms,仍然可以优化。尽量减少不必要的函数调用,将max函数调用改为if判断语句测可以节省3ms。
if (tmpSum > maxSum)
maxSum = tmpSum;