栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

53. 最大子数组和(LeetCode)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

53. 最大子数组和(LeetCode)

题目

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

子数组 是数组中的一个连续部分。

思路:

一维dp动态数组将每一个小数组的最优值存入 max

dp[i]用来决定是否将第i个元素加入到连续子数组中 

动态规划转移方程:

dp[i]= max{ dp(i-1) + nums[i], nums[i] }
加入之后还需要比较之前的最大值与加入后的最大值

max=Math.max(max,dp[i]);

class Solution {

    public int maxSubArray(int[] nums) {

        int max=nums[0];

        int len=nums.length;

        int []dp=new int[len];

        dp[0]=nums[0];

        for(int i=1;i

            dp[i]=Math.max(dp[i-1]+nums[i],nums[i]);

            max=Math.max(max,dp[i]);

        }

        return max;

    }

}

代码优化:

方法1

此题 主要是解决dp[i-1]+nums[i]与nums[i]的大小 从而决定是否将nums[i]加入到子数组中

再将此时的最大和 和 之前的最大和作比较 选出到目前为止最大的和

public static int maxSubArray(int[] nums) {
        int dp= 0, maxSums = nums[0];
        for (int x : nums) {
            dp = Math.max(dp + x, x);
            maxSums = Math.max(maxSums, dp);
        }
        return maxSums;
    }
public static void main(String[] args) {
    int[] nums = {1, 2, 3, -4, -5, 6, 7, -8, 9, 10, 11, 12};
    int maxAns=maxSubArray(nums);
    System.out.println(maxAns);
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/750036.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号