问题描述:在一个数列中找到一个连续的子数列,使得该子数列的和最大。
Kadane算法
扫描一次整个数列的所有值,在每个点计算以该点为结束点的子数列的最大和。该子数列由两部分组成:以前一个位置为结束点的最大子数列、该点的数值。(最优子结构,因此是动态规划问题)
这个问题很早就被Jon Bentley讨论过(Sep. 1984 Vol. 27 No. 9 Communications of the ACM P885)
下面这段是论文中算法描述:
algorithm that operates on arrays: it starts at the left end (element A[1]) and scans through to the right end (element A[n]), keeping track of the maximum sum subvector seen so far.
The maximum is initially A[0]. Suppose we've solved the problem for A[1 .. i - 1]; how can we extend that to A[1 .. i]? The maximum sum in the first I elements is either the maximum sum
in the first i - 1 elements (which we'll call MaxSoFar), or it is that of a subvector that ends in position i (which we'll call MaxEndingHere).
C++实现:
int maxSubArray(vector<int>& nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for(int i = 1; i < nums.size(); ++i){
maxEndingHere = max(nums[i], maxEndingHere + nums[i]);
maxSoFar = max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
该问题的一个变种是:如果数列中含有负数元素,允许返回长度为零的子数列,将以上代码稍作修改即可:
int maxSubArray(vector<int>& nums) {
int maxSoFar = 0;
int maxEndingHere = 0;
for(int i = 0; i < nums.size(); ++i){
maxEndingHere = max(0, maxEndingHere + nums[i]);
maxSoFar = max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
LeetCode121. Best Time to Buy and Sell Stock
一个数组代表一支股票每天的价格,买入卖出算一次交易,最多交易一次,求最大收益。
分析:这道题可以转化为求最大子数列问题
例如[1, 7, 4, 11], 可以转换为[0, 6, -3, 7],然后计算该数组的最大子数列和即可(注意如果最大子数列和为负数,要返回0,即上面的变体)
int maxProfit(vector<int>& prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.size(); ++i){
maxCur = max(0, maxCur + prices[i] - prices[i - 1]);
maxSoFar = max(maxSoFar, maxCur);
}
return maxSoFar;
}