您的位置:首页 > 其它

Leetcode-maximum-subarray

2016-06-30 13:27 381 查看


题目描述

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.

click to show more practice.
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.

动态规划入门级题目:最大子数组

前面的博文中其实介绍了这一题,我在调试的时候,仍然出现了问题,子数组连续的,这点很重要。

public class Solution {
public int maxSubArray(int[] A) {
int max = A[0];
int res = A[0];
for(int i=1; i<A.length; i++){
res = Math.max(A[i], res+A[i]); //这里需要注意,是A[i]和res+A[i]的比较,不是和A[i]+max的比较,这点非常重要。
max = Math.max(res, max);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: