#LeetCode匠#最大子序和

105 阅读1分钟

「这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战」。

使用动态规划的两种不同实现解法

题目描述

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

题目示例

题目解法

解法一:动态规划-精简计算

/**
 * 动态规划-精简法
 */
class Solution {
    public int maxSubArray(int[] nums) {
        int curSum = 0;
        int resMax = nums[0];
        for (int num : nums) {
            // 当前累加最大值
            curSum = Math.max(curSum + num, num);
            // 累计遍历最大值
            resMax = Math.max(resMax, curSum);
        }
        return resMax;
    }
}

解法二:动态规划-取正数之和

/**
 * 累计加和取正数法
 */
class Solution {
    public int maxSubArray(int[] nums) {
        // 返回最大值
        int resMax = nums[0];
        // 当前计算值
        int sumValue = 0;
        for (int num : nums) {
            if (sumValue > 0){
                sumValue += num;
            }else{
                sumValue = num;
            }
            // 保持取最大值
            resMax = Math.max(resMax, sumValue);
        }
        return resMax;
    }
}

LeetCode原题链接:leetcode-cn.com/problems/ma…