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<len;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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

名称是:小小小灵通

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值