leetcode53

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

思路:动态规划的思想,申请一个同样长度的数组res[]做状态记录。res[i]表示以nums[i]结尾的连续子数组的最大和的值,它等于res[i - 1] + nums[i] 和 nums[i]中的较大值。

public int maxSubArray(int[] nums) {
    if(nums == null || nums.length == 0)
        return 0;
    int[] res = new int[nums.length];
    res[0] = nums[0];
    int max = res[0];
    for (int i = 1; i < nums.length; i++) {
        res[i] = (nums[i] + res[i - 1] > nums[i])? nums[i] + res[i - 1]: nums[i];
        if(res[i] > max)
            max = res[i];
    }
    return max;
}

猜你喜欢

转载自blog.csdn.net/qwerrfxgj/article/details/89399915