剑指offer 42. 连续子数组的最大和

剑指offer 42. 连续子数组的最大和

题目描述

在这里插入图片描述

解题思路

注意,此题是找连续子数组的最大值,思路是dp。

为什么不是前缀和?

前缀和的题目描述虽然也是连续子数组 ,但一定要有 “和为K” 的字眼,注意区分。

class Solution {
    
    
    public int maxSubArray(int[] nums) {
    
    
        //定义:dp[i]表示以nums[i]结尾的子数组和的最大值
        int[] dp = new int[nums.length];
        //base case
        dp[0] = nums[0];
        int res = nums[0];

        for (int i = 1; i < nums.length; i++) {
    
    
            dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
            res = Math.max(res, dp[i]);
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115280181