首页 > 代码库 > 53. Maximum Subarray

53. Maximum Subarray

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.

此题和Maximum product subarray很像,只不过比那个简单一点,也是用的动态规划做法做的,首先思考最优子结构性质,前面的最优解+当前数组值和当前数组值进行比较,取较大的值,直到求到全局解。重叠子问题也存在,将前面的最优解的值存放在了res里面,代码如下:

<style>p.p1 { margin: 0.0px 0.0px 2.0px 0.0px; font: 14.0px "Helvetica Neue"; color: #454545 }</style>

public class Solution {

    public int maxSubArray(int[] nums) {

        if(nums.length==0) return 0;

        int res = nums[0];

        int cur = nums[0];

        for(int i=1;i<nums.length;i++){

            cur = Math.max(cur+nums[i],nums[i]);

            res = Math.max(cur,res);

        }

        return res;

    }

}

53. Maximum Subarray