`

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.

一道动态规划的题目,解决这道题我们维护两个变量,一个局部变量current来记录当前状态下的最大值,然后用一个全局变量result来记录最大的结果。代码如下:
public class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) return Integer.MIN_VALUE;
        int cur = nums[0];
        int result = nums[0];
        for(int i = 1; i < nums.length; i++) {
            cur = Math.max(nums[i], cur + nums[i]);
            result = Math.max(cur, result);
        }
        return result;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics