Leetcode 53. Maximum Subarray(最大子数组)

本文深入探讨了寻找数组中最大连续子数组和的算法,通过动态规划思想,提出了一种简洁高效的解决方案。该算法能在O(n)的时间复杂度内找到使连续子数组和最大的子序列。

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

是给一个数组,在数组中找出元素相加和最大的连续子数组。

思路:
因为题中要求是连续子数组,连续很重要,省去了很多问题。
所以子数组只要一中断就要重新开始。

选择连续的思路可以看哪个和更大,是前面的部分加上当前元素更大,还是不要前面的了,从当前元素开始,只看当前元素本身更大。

相当于小型DP,而且最大值不一定在最后出现,要保存过程中的最大值。

    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int localMax = nums[0];
        int result = nums[0];
        
        for(int i = 1; i < nums.length; i++) {
            localMax = Math.max(localMax + nums[i], nums[i]);
            result = Math.max(result, localMax);
        }
        
        return result;
    }
最大子数组和问题旨在寻找给定整数数组连续子数组最大和。在C++中,可以使用经典的 **Kadane's Algorithm** 来高效解决这一问题。该算法基于动态规划的思想,能够在 **O(n)** 的时间复杂度内完成计算。 以下是一个完整的 C++ 实现示例,展示了如何使用 Kadane’s 算法来求解最大子数组和: ```cpp #include <iostream> #include <vector> #include <climits> using namespace std; int maxSubArray(vector<int>& nums) { int max_current = nums[0]; int max_global = nums[0]; for (size_t i = 1; i < nums.size(); ++i) { max_current = max(nums[i], max_current + nums[i]); max_global = max(max_global, max_current); } return max_global; } int main() { vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; int result = maxSubArray(nums); cout << "Maximum Subarray Sum: " << result << endl; return 0; } ``` ### 代码说明: - `max_current` 表示当前子数组最大和。 - `max_global` 用于记录遍历过程中出现的最大子数组和。 - 在每次迭代中,算法决定是继续扩展当前子数组,还是以当前元素作为新的子数组的起点。 - 最终,`max_global` 将保存整个数组最大子数组的和。 ### 时间和空间复杂度: - **时间复杂度**:O(n),其中 n 是数组的长度。 - **空间复杂度**:O(1),仅使用了常数级别的额外空间。 这种实现方式非常高效,适用于大规模输入数据,例如在 LeetCode 等在线评测平台上,能够很好地应对数据范围限制(如 `1 <= nums.length <= 10^5`)[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值