Description of the problem: find a number of consecutive sub-columns in a series, so that the number of columns and the sub-maximum.
Kadane algorithm
All scans a whole series of values, calculated in the point of the end point and at each point the maximum number of sub-columns. The sub-series consists of two parts: a previous position to the end point of the maximum number of sub-columns, the value of the point. (Optimal substructure, and therefore is a dynamic programming problem)
This problem has long been discussed Jon Bentley (Sep. 1984 Vol. 27 No. 9 Communications of the ACM P885)
Below this algorithm is described in the paper:
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 ++ implementation:
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;
}
The variant is a problem: if the number of columns contained in the negative elements, the number of columns allowed to return to sub-zero length, slight modifications to the code above:
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
An array represents the daily price of a stock, once considered buying and selling transaction, the transaction at most once, seeking the maximum benefit.
Analysis: This question can be transformed for the sake of the maximum number of columns in the sub-problems
For example [1, 7, 4, 11], can be converted to [0, 6, -3, 7], and then calculates the maximum number of sub-columns of the array and to (Note that the maximum number of sub-columns and negative, to return to 0, i.e. above variants)
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;
}