Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
最大字子串的问题,该问题无论是各种面试题还是编程珠玑异或各种算法书中都是一道经典的题目。可惜每次都是草草地复制代码,没能深入理解其中的精髓,时间稍微久一点就会忘记。特记录如下:
O(n)算法
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max = INT_MIN;
int sum = 0;
int i = 0;
while(i < nums.size())
{
sum += nums[i];
if(max < sum)
max = sum;
if(sum < 0)
sum = 0;
i++;
}
return max;
}
};
更新2019.02.12:
前段时间面试时遇到了相同的题目,当时很快就写出来了,但是漏掉了数组都为负值的情况。使用动态规划的思想来解释一下程序。
如果使用函数f(i)来表示第i个数字结尾的子数组的最大和,则我们的目标是求出max(f(i))。其中f(i)可以用如下状态转移方程为来表示:
因此,我们使用sum来表示f(i),max来表示max(f(i)),便有了以上代码。