题目描述:
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.
题解:
题目链接:https://leetcode.com/problems/maximum-subarray/
最近在复习DP,把这道题用DP再做一遍;题意很简单,就是求一个和最大的子序列,和LIS(最长上升子序列)
有点类似;构造状态转移方程:
D
P
(
i
)
=
m
a
x
(
D
P
(
i
−
1
)
+
n
u
m
s
(
i
)
,
n
u
m
s
(
i
)
)
DP(i) = max(DP(i-1) + nums(i), nums(i))
DP(i)=max(DP(i−1)+nums(i),nums(i))
D
P
(
i
)
DP(i)
DP(i):代表以
n
u
m
s
(
i
)
nums(i)
nums(i)结尾的序列的最大值。
关于DP可以查看DP基础。
DP解法:
class Solution{
public:
int maxSubArray(vector<int> &nums){
int len = nums.size(), dp[len], sum;
dp[0] = sum = nums[0];
for(int i=1; i<len; i++){
dp[i] = max(dp[i-1] + nums[i], nums[i]);
sum = max(sum, dp[i]);
}
return sum;
}
};
这道题的解法有很多:也可以使用Kadane's algorithm
,其实和DP的思路有点像了。
理解此算法的关键在于:
- 先将问题进行拆分, 指定数组中某一个元素 A[i],作为最大子数列的末尾元素时, 能找到的最大子数列的求和值是多少。
- A[i] 作为末尾元素时能找到的最大子数列 必然为A[i] 本身,或是 A[i-1] 作为末尾元素时能找到的最大子数列加上 A[i]。
int maxSubArray(vector<int>& nums) {
int curSum, maxSum;
curSum = maxSum = nums[0];
for(int i=1; i < nums.size(); i++){
curSum = max(nums[i], curSum + nums[i]);
maxSum = max(curSum, maxSum);
}
return maxSum;
}
分治算法:
// Divide and Conquer 分治算法,求每个部分的最大值
int maxSubArray(vector<int>& nums) {
maxSub(nums, 0, nums.size()-1);
}
int maxSub(vector<int>& nums, int l, int r){
if(l > r){
return INT_MIN;
}
int m = l + (r - l)/2;
int lmax = maxSub(nums, l, m-1);
int rmax = maxSub(nums, m+1, r);
int ml = 0, mr = 0;
for(int i = m-1, sum = 0; i >= l; i--){
sum += nums[i];
ml = max(ml, sum);
}
for(int i = m+1, sum = 0; i <= r; i++){
sum += nums[i];
mr = max(mr, sum);
}
return max(max(lmax, rmax), ml + mr + nums[m]);
}
更多代码可以查看github
。