zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    .NET5 ABP框架(二)- WebApi
    找不到版本为(>=2.0.3)的包NETStandard.Library -在 Microsoft Visual Stduio Offine Packages 中找到2个版本[ 最接近:1.6.1 ]
    .NET5 ABP框架(一)
    开学第一节课
    开学考试
    参考:
    安装git
    org.apache.thrift.transport.TTransportException: Could not create ServerSocket on address 0.0.0.0/0.0.0.0:9083.
    hive insert 出现问题
    hive开启远程连接方法
  • 原文地址:https://www.cnblogs.com/lfeng1205/p/7504958.html
Copyright © 2011-2022 走看看