题目:
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
.
More practice:
解答:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution {
public:
int maxSubArray(int A[], int n) {
int sum = A[0];
int max = A[0];
for(int i = 1; i < n; i++) {
sum = sum + A[i];
if(sum < A[i]) {
sum = A[i];
}
if(sum > max) {
max = sum;
}
}
return max;
}
};
思路:
动态规划的思想,max和sum首先初始化为数组第一个数,然后从数组第二个数遍历整个数组。
sum记录某一子串的和,当遍历到某一位时,如果加上这一位的数,sum变得比这一位的数字还小,那么之前的最大和子串完全没有必要加上当前这一位,所以sum赋值为当前这一位,其实意味着从这一位开始重新计算sum,即把这一位当成是子串的起点。
sum更新(加上当前位)后,需要与max比较,如果比max大,则更新max的值。
由此,便可以得到最大和子串的值。