Leetcode-maximum-subarray

来源:互联网 发布:matlab在线编程 编辑:程序博客网 时间:2024/05/01 12:56

题目描述


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;    }}


0 0
原创粉丝点击