LeetCode刷题笔记 53 / 剑指Offer 42

博客围绕给定整数数组,求最大和的连续子数组问题展开。给出了暴力法,但不推荐。重点介绍了贪心算法,每步选最佳方案,遍历数组更新相关值;还介绍了动态规划,沿数组移动并在原数组修改,两种算法时间和空间复杂度均为 O(N) 和 O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
例:输入: [-2,1,-3,4,-1,2,1,-5,4],输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

我的答案:
1)暴力法(太慢了,不推荐)

class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        if(n == 1) return nums[0];
        int max = nums[0];
        int sum = 0;
        for(int i = 0; i < n-1; i++){
       		if(nums[i] < 0 && nums[i] < nums[i+1])
                continue;
            max = Math.max(max,nums[i]);
            sum = nums[i];
            for(int j = i+1; j < n; j++){
                sum = sum + nums[j];
                if(sum > max)
                    max = sum;
            } 
        }
        max = Math.max(max,nums[n-1]);
        return max;
    }
}

讨论区好的方法:
1.贪心算法
每一步都选择最佳方案,到最后就是全局最优的方案。
如果该元素和前面的元素相加没有使自己变大,则抛弃前面的元素
该算法通用且简单:遍历数组并在每个步骤中更新:
当前元素、当前元素位置的最大和、迄今为止的最大和
在这里插入图片描述

public int maxSubArray(int[] nums) {
    int localMax = nums[0], globalMax = nums[0];
    for(int i = 1; i < nums.length; i++) {
        localMax = Math.max(nums[i] + localMax, nums[i]);
        globalMax = Math.max(localMax, globalMax);
    }
    return globalMax;
}

时间复杂度:O(N)。只遍历一次数组。
空间复杂度:O(1)。只使用了常数空间。

2.动态规划
沿数组移动并在原数组修改。

class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length, maxSum = nums[0];
        for(int i = 1; i < n; ++i) {
            if (nums[i - 1] > 0) nums[i] += nums[i - 1];
            maxSum = Math.max(nums[i], maxSum);
        }
        return maxSum;
    }
}

时间复杂度:O(N)。只遍历一次数组。
空间复杂度:O(1)。只使用了常数空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值