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.
Difficulty:Easy
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:Dynamic Programming
- Time complexity : O ( n ) O\left ( n \right ) O(n)
- Space complexity :
O
(
1
)
O\left ( 1 \right )
O(1)
思路:
回忆一下动态规划的四个步骤:
1、描述优解的结构特征。
2、递归地定义一个最优解的值。
3、自底向上计算一个最优解的值。
4、从已计算的信息中构造一个最优解。
核心是找到子问题的结构:
如果将子问题分解成maxSubArray(int A[], int i, int j)
,很难找到子问题和原问题的关系
换个分解方式maxSubArray(int A[], int i)
,子问题和原问题的关系如下
maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
// 第一版, 写的不优雅,比较烂
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_sum = INT_MIN;
int temp_sum = 0;
for (int i = 0; i < nums.size(); i++) {
temp_sum += nums[i];
if (temp_sum > max_sum)
max_sum = temp_sum;
if (temp_sum <= 0)
temp_sum = 0;
}
return max_sum;
}
};
// 第二版, 优化版
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_sum = INT_MIN;
int temp_sum = 0;
for (int i = 0; i < nums.size(); i++) {
temp_sum = nums[i] + (temp_sum > 0 ? temp_sum : 0);
max_sum = max(max_sum, temp_sum);
}
return max_sum;
}
};