LeeCode 53. 最大子序和

文章目录

  • 题目
  • 题解
  • 代码

题目

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

LeeCode 53. 最大子序和_第1张图片

题解

动态规划

我们可以记录之前和,还有最大和,如果说之前的和<0,说明之前的总数太小了,剔除掉。

分类:

  1. 如果是一直变大的,比如[1,2,3],那么之前的和加上当前的数,最大和就是之前最大和跟当前和比较,取Math.max
  2. 如果是中间忽然变小,之前和小于0,比如[1,-2,-3],这时我们把之前和清零,然后现在的和变成当前的数,方便后续判断,这时最大和就是之前最大和跟当前的数比,如果现在的数都比之前的和大,那么剔除掉。

代码

class Solution {
     
    public int maxSubArray(int[] nums) {
     
        if(nums.length == 1){
     
            return nums[0];
        }
        int max = nums[0];
        int firstSum = 0;
        for(int a:nums){
     
            if(firstSum<0){
     
                firstSum = a;
                max = Math.max(max,a);
            }else{
     
                firstSum = firstSum+a;
                max = Math.max(max,firstSum);
            }
            
        }
        return max;
    }
}

你可能感兴趣的:(算法,leetcode)