LeetCode之连续子数组的最大和

题目描述

在数组中找到连续的子阵列(包含至少一个数字),其数量最大。例如:给一个数组{-2,1,-3,4,-1,2,1,-5,4},连续的子序列[4,1,2,1]具有最大的和= 6。

分析

当我们从头到尾遍历这个数组的时候,对于数组里的一个整数,它有两种选择:1、加入之前的SubArray;2、自己另起一个SubArray。

如果之前的SubArray的总体的和大于0的话,我们认为其对后续结果是有贡献的。这种情况下我们选择加入之前的SubArray。

如果之前的SubArray的总体和为0或者小于0的话,我们认为其对后续结果是没有贡献的,甚至是有害的(小于0时)。这种情况下我们选择以这个数字开始,另起一个SubArray。

设状态为f[j],表示以S[j]结尾的最大连续子序列和,则状态转移方程如下:

$f[j]=max{f[j-1]+S[j],S[j]}$,其中1≤j≤n

target=max{f[j]},其中1≤j≤n

Java代码

package dynamicPlanning;

/**
 * Created by Feng on 2017/9/11.
 */
public class MaximumSubarray {

    public int maxSubArray(int[] nums) {
        int result = Integer.MIN_VALUE;
        int max = 0;

        for (int i = 0; i < nums.length; i++) {
            max = Math.max(max + nums[i], nums[i]);
            result = Math.max(result, max);
        }

        return result;
    }
}

测试代码:

package dynamicPlanning;

import org.junit.Test;

/**
 * Created by Feng on 2017/9/11.
 */
public class MaximumSubarrayTest {

    MaximumSubarray maximumSubarray = new MaximumSubarray();

    @Test
    public void maxSubArray() throws Exception {
        int[] nums = {6, -3, -2, 7, -15, 1, 2, 2};
        int result = maximumSubarray.maxSubArray(nums);
        System.out.println(result);
    }
}
原文地址:https://www.cnblogs.com/lfeng1205/p/7504958.html