Leetcode 0053. Maximum Subarray
53. Maximum Subarray
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
1 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] |
Example 2:
1 | Input: nums = [1] |
Example 3:
1 | Input: nums = [5,4,-1,7,8] |
题目大意
给定一个整数数组 nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
例如:
- 输入
nums = [-2,1,-3,4,-1,2,1,-5,4],输出6(对应子数组[4,-1,2,1]); - 输入
nums = [1],输出1(唯一子数组[1])。
解题思路
核心思路是动态规划(Kadane 算法),通过遍历数组并实时计算 “以当前元素结尾的最大子数组和”,从而高效找到全局最大和:
- 状态定义:
设dp[i]表示以nums[i]结尾的最大子数组和,则有两种选择:- 将
nums[i]加入前一个子数组:dp[i] = dp[i-1] + nums[i]; - 以
nums[i]为起点重新开始子数组:dp[i] = nums[i]。
因此状态转移方程为:dp[i] = max(nums[i], dp[i-1] + nums[i])。
- 将
- 空间优化:
由于dp[i]仅依赖dp[i-1],无需存储整个dp数组,只需用一个变量current_sum记录上一个状态,将空间复杂度从 O (n) 降至 O (1)。 - 全局最大值跟踪:
遍历过程中,用max_sum记录所有current_sum中的最大值,即为结果。
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

