Kadane's algorithm(Kadane算法)
- 最大子数列
- 两个变量:max_ending_here(将当前元素x强制作为最后一个元素)、max_so_far(遍历至当前元素时,最大的和)
int maxSubArray(vector<int> nums){
int max_so_far=max_ending_here=nums[0];
for(int i=0;i<nums.size();i++){
max_ending_here=max(nums[i],max_ending_here+nums[i]);
max_so_far=max(max_ending_here,max_so_far);
}
return max_so_far;
}
121 | 48.6% | Easy | ||||
122 | 53.5% | Easy | ||||
123 | 35.2% | Hard | ||||
188 | 27.1% | Hard | ||||
309 | 45.0% | Medium | ||||
714 | 52.1% | Medium |
121. Best Time to Buy and Sell Stock
(最多一次交易)
Easy
3329149FavoriteShare
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
-
使用Kadane's algorithm(Kadane算法)思想:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0 || prices.size()==1) return 0;
int max_ending_here=0,max_so_far=0;
int min=prices[0];
for(int i=1;i<prices.size();i++){
if(prices[i]<min) min=prices[i];
max_ending_here=max(prices[i]-min,0);
max_so_far=max(max_so_far,max_ending_here);
}
return max_so_far;
}
};
- Runtime: 4 ms, faster than 98.18% of C++ online submissions for Best Time to Buy and Sell Stock.
- Memory Usage: 9.5 MB, less than 88.99% of C++ online submissions for Best Time to Buy and Sell Stock.
- Next challenges:
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock with Cooldown
- max_ending_here不用维持min值:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0 || prices.size()==1) return 0;
int max_ending_here=0,max_so_far=0;
for(int i=1;i<prices.size();i++){
max_ending_here=max(max_ending_here+prices[i]-prices[i-1],0);
max_so_far=max(max_so_far,max_ending_here);
}
return max_so_far;
}
};
- Runtime: 4 ms, faster than 98.18% of C++ online submissions for Best Time to Buy and Sell Stock.
- Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock.
- 以下简单遍历:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res=0;
if(prices.size()<=1) return res;
int minn=prices[0],maxx=prices[prices.size()-1];
for(int i=0;i<prices.size()-1;i++){
if(minn>prices[i]) minn=prices[i];
maxx=prices[i+1];
for(int j=i+1;j<prices.size();j++){
if(maxx<prices[j]) maxx=prices[j];
}
if(res<maxx-minn) res=maxx-minn;
}
return res;
}
};
- Runtime: 528 ms, faster than 12.39% of C++ online submissions for Best Time to Buy and Sell Stock.
- Memory Usage: 9.5 MB, less than 83.49% of C++ online submissions for Best Time to Buy and Sell Stock.
122. Best Time to Buy and Sell Stock II
(可以多次交易)
Easy
13451439FavoriteShare
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int cash=0,hold=-prices[0];
for(int i=1;i<prices.size();i++){
cash=max(cash,hold+prices[i]);
hold=max(hold,cash-prices[i]);
}
return cash;
}
};
- Runtime: 8 ms, faster than 61.78% of C++ online submissions for Best Time to Buy and Sell Stock II.
- Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock II.
- Next challenges:
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
123. Best Time to Buy and Sell Stock III
Hard
142959FavoriteShare
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int sell1=0,sell2=0,buy1=INT_MIN,buy2=INT_MIN;
for(int i=0;i<prices.size();i++){
buy1=max(buy1,-prices[i]);
sell1=max(sell1,buy1+prices[i]);
buy2=max(buy2,sell1-prices[i]);
sell2=max(sell2,buy2+prices[i]);
}
return sell2;
}
};
- Runtime: 8 ms, faster than 71.89% of C++ online submissions for Best Time to Buy and Sell Stock III.
- Memory Usage: 9.5 MB, less than 78.57% of C++ online submissions for Best Time to Buy and Sell Stock III.
- Next challenges:
- Best Time to Buy and Sell Stock IV
- Maximum Sum of 3 Non-Overlapping Subarrays
- 思路借鉴:https://blog.csdn.net/u012501459/article/details/46514309
- 假设手上最开始只有0元钱,那么如果买入股票的价格为price,手上的钱需要减去这个price,如果卖出股票的价格为price,手上的钱需要加上这个price。
- Buy1[i]表示前i天做第一笔交易买入股票后剩下的最多的钱;
- Sell1[i]表示前i天做第一笔交易卖出股票后剩下的最多的钱;
- Buy2[i]表示前i天做第二笔交易买入股票后剩下的最多的钱;
- Sell2[i]表示前i天做第二笔交易卖出股票后剩下的最多的钱;
- Sell2[i]=max{Sell2[i-1],Buy2[i-1]+prices[i]}
- Buy2[i]=max{Buy2[i-1],Sell[i-1]-prices[i]}
- Sell1[i]=max{Sell[i-1],Buy1[i-1]+prices[i]}
- Buy1[i]=max{Buy[i-1],-prices[i]}
- 另一种思路:
- 定义A[i]为前i天赚的最大数目的钱,minPrice表示从0到第i-1天中的最低价格,因此:A[0]=0,A[1]=max(prices[1]-prices[0],A[0]),A[2]=max(A[1],prices[2]-minPrice),...,A[i]=max(A[i-1],prices[i]-minPrice).
- 另一次从后往前扫描,定义B[i]表示从第i天到最后一天n能赚的最大数目的钱,maxPrice表示第i+1天到n天的最高价格,因此:B[n]=0,B[n-1]=max(B[n],maxPrice-prices[n-1]),B[n-2]=max(B[n-1],maxPrice-prices[n-2]),...,B[i]=max(B[i+1],maxPrice-prices[i]).
- 那么以第i天为分割点能够赚的最多数目的钱为:A[i]+B[i],转化为求解max{A[i]+B[i]},时间复杂度:O(n),空间复杂度:O(n).
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int n=prices.size(),res=0;
vector<int> A(n,0),B(n,0);
int minPrice=prices[0],maxPrice=prices[n-1];
for(int i=1;i<n;i++){
A[i]=max(A[i-1],prices[i]-minPrice);
if(minPrice>prices[i]) minPrice=prices[i];
B[n-i-1]=max(B[n-i],maxPrice-prices[n-i-1]);
if(maxPrice<prices[n-i-1]) maxPrice=prices[n-i-1];
}
for(int i=0;i<n;i++){
if(res<A[i]+B[i]) res=A[i]+B[i];
}
return res;
}
};
- Runtime: 8 ms, faster than 71.89% of C++ online submissions for Best Time to Buy and Sell Stock III.
- Memory Usage: 9.8 MB, less than 35.71% of C++ online submissions for Best Time to Buy and Sell Stock III.
188. Best Time to Buy and Sell Stock IV
(最多k次交易)
Hard
98261FavoriteShare
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input: [2,4,1], k = 2 Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2 Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
309. Best Time to Buy and Sell Stock with Cooldown
(可以多次交易,买完之后的第一天不能买进,成为cooldown)
Medium
164762FavoriteShare
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int i=1,size=prices.size();
vector<int> s0(size,0),s1(size,0),s2(size,0);
s0[0]=0;s1[0]=-prices[0];s2[0]=INT_MIN;
//s0:休息日,s1:持有,s2:卖掉(不持有)
for(i=1;i<size;i++){
s0[i]=max(s0[i-1],s2[i-1]);
//休息日,要么是昨天刚卖掉(s2[i-1]),要么是和昨天一样没有交易(s0[i-1])
s1[i]=max(s0[i-1]-prices[i],s1[i-1]);
//持有,要么是从休息日刚过来卖掉的(s0[i-1]-prices[i]),要么是和昨天一样没有交易(s1[i-1])
s2[i]=s1[i-1]+prices[i];
//卖掉,下一个状态是s0
}
return max(s0[size-1],s2[size-1]);
}
};
- Runtime: 0 ms, faster than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock with Cooldown.
- Memory Usage: 8.7 MB, less than 88.89% of C++ online submissions for Best Time to Buy and Sell Stock with Cooldown.
- Next challenges:
- Burst Balloons
- Maximum Length of Pair Chain
- Soup Servings
- 思路借鉴:https://www.cnblogs.com/jdneo/p/5228004.html
714. Best Time to Buy and Sell Stock with Transaction Fee
(可以多次交易,每次交易/卖出时有手续费,求买卖股票的最大收益)
Medium
110033FavoriteShare
Your are given an array of integers prices
, for which the i
-th element is the price of a given stock on day i
; and a non-negative integer fee
representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
- The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Note:
0 < prices.length <= 50000
.0 < prices[i] < 50000
.0 <= fee < 50000
.
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int cash=0,hold=-prices[0];
//cash表示该天结束时,若未持有股票,手中的最大价值
//hold表示该天结束时,若持有股票,手中的最大价值
for(int i=1;i<prices.size();i++){
cash=max(cash,hold+prices[i]-fee);
//未持有股票:当天没买(cash)/ 当天刚卖(hold+prices[i]-fee)
hold=max(hold,cash-prices[i]);
//持有股票:当天没卖(hold)/ 当天刚买(cash-prices[i])
}
return cash;
}
};
- Runtime: 128 ms, faster than 97.59% of C++ online submissions for Best Time to Buy and Sell Stock with Transaction Fee.
- Memory Usage: 15 MB, less than 94.12% of C++ online submissions for Best Time to Buy and Sell Stock with Transaction Fee.
- Next challenges:
- 3Sum Closest
- Triangle
- Remove Sub-Folders from the Filesystem
- 思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/79888528