【LeetCode】53. Maximum Subarray

最大子数组和算法解析

我的相关文章:

【1】牛客网在线编程专题《剑指offer-面试题31》连续子数组的最大和


53. Maximum Subarray

Description:

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.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 解题思路:

(1)举例分析数组的规律

已经AC的代码:

public class solutionMaxSubArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
		System.out.println(maxSubArray(arr));
	}
	
    public static int maxSubArray(int[] nums) {
       int  sum = Integer.MIN_VALUE;
       int currentSum = 0;
       for(int i=0; i<nums.length; i++) {
    	   currentSum += nums[i];
    	   if(currentSum < nums[i]) {
    		   currentSum = nums[i];
    	   }
    	   if(currentSum > sum) {
    		   sum = currentSum;
    	   }
       }
       return sum;
    }

}

(2)动态规划的解法

public class solutionMaxSubArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
		System.out.println(maxSubArray(arr));
	}
	
    public static int maxSubArray(int[] nums) {
    	int sum = Integer.MIN_VALUE;
    	int currentSum = 0;
    	for(int i=0; i<nums.length; i++) {
    		if(currentSum <= 0)
    			currentSum = nums[i];
    		else
    			currentSum += nums[i];
    		if(currentSum > sum)
    			sum = currentSum;
    	}
		return sum;
    }
}

Python已经AC的代码:

class Solution:
	def maxSubArray(self, nums):
		nums_len = len(nums)
		result = [0 for i in range(nums_len)]
		maxSum = result[0] = nums[0]
		for i in range(1, nums_len):
			if nums[i] >= result[i-1] + nums[i]:
				result[i] = nums[i]
			else:
				result[i] = result[i-1] + nums[i]

			if maxSum <= result[i]:
				maxSum = result[i]
		return maxSum


if __name__ == '__main__':
	nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
	sol = Solution()
	print(sol.maxSubArray(nums))

 

你提供的代码是 **LeetCode53题:最大子数组和(Maximum Subarray)** 的标准动态规划解法,使用了 **Kadane 算法**,是一种非常高效的一维动态规划算法。它可以在 **O(n)** 时间复杂度内找到连续子数组的最大和。 --- ## ✅ 代码解析与完整 VS2022 可运行版本 以下是适合在 **Visual Studio 2022 (VS2022)** 中运行的完整代码版本,包含 `vector`、主函数和测试用例。 ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { int pre = 0, maxAns = nums[0]; for (const auto& x : nums) { pre = max(pre + x, x); // 当前元素与当前元素+前面序列和的最大值 maxAns = max(maxAns, pre); // 更新全局最大值 } return maxAns; } }; // 主函数测试 int main() { Solution sol; vector<int> nums; // 测试用例 1 nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n最大子数组和为: " << sol.maxSubArray(nums) << endl << endl; // 测试用例 2 nums = {1}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n最大子数组和为: " << sol.maxSubArray(nums) << endl << endl; // 测试用例 3 nums = {5, 4, -1, 7, 8}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n最大子数组和为: " << sol.maxSubArray(nums) << endl << endl; // 测试用例 4 nums = {-1, -2, -3, -4}; cout << "输入数组: "; for (int num : nums) cout << num << " "; cout << "\n最大子数组和为: " << sol.maxSubArray(nums) << endl << endl; return 0; } ``` --- ## ✅ 示例输出 ``` 输入数组: -2 1 -3 4 -1 2 1 -5 4 最大子数组和为: 6 输入数组: 1 最大子数组和为: 1 输入数组: 5 4 -1 7 8 最大子数组和为: 23 输入数组: -1 -2 -3 -4 最大子数组和为: -1 ``` --- ## ✅ 算法逻辑详解 ### ✅ 问题背景 给定一个整数数组 `nums`,找到一个具有最大和的连续子数组(子数组至少包含一个元素),返回其最大和。 ### ✅ 解法思路:Kadane 算法(贪心 + 动态规划) #### 核心思想: - 维护一个变量 `pre`,表示以当前元素结尾的最大子数组和。 - 对于每个元素 `x`: - 如果 `pre + x` 比 `x` 大,说明可以继续扩展当前子数组; - 否则,舍弃之前的子数组,从当前元素重新开始。 - 每次更新全局最大值 `maxAns`。 #### 示例说明: ``` nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] 遍历过程: pre = -2 → maxAns = -2 pre = max(-2 + 1, 1) = 1 → maxAns = 1 pre = max(1 + (-3), -3) = -2 → maxAns = 1 pre = max(-2 + 4, 4) = 4 → maxAns = 4 ... 最终 maxAns = 6 ``` --- ## ✅ 时间与空间复杂度 | 类型 | 复杂度 | 说明 | |------|--------|------| | 时间复杂度 | O(n) | 只遍历一次数组 | | 空间复杂度 | O(1) | 只使用常数级额外空间 | --- ## ✅ 常见问题排查(VS2022) 1. **编译错误** - 确保包含 `<vector>` 和 `<algorithm>` - 使用 `using namespace std;` 或加上 `std::` 前缀 2. **运行时错误** - 注意空数组处理(虽然题目保证至少一个元素) - 确保 `max()` 函数参数正确 3. **逻辑错误** - 初始化 `maxAns` 为 `nums[0]` 是关键 - `pre` 的初始值应为 `0` --- ## ✅ 对比其他解法 | 解法 | 时间复杂度 | 空间复杂度 | 特点 | |------|------------|------------|------| | Kadane 算法(当前方法) | O(n) | O(1) | 最优解,推荐 | | 暴力枚举所有子数组 | O(n²) | O(1) | 简单但低效 | | 分治法(归并思想) | O(n log n) | O(log n) | 面试拓展思路 | | 动态规划(dp 数组) | O(n) | O(n) | 易理解,但空间略高 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值