Best time to buy and buy stock I
Only one operation: Minimum value that appears before the premin record is maintained
The Code is as follows:
int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; int profit = 0; int preMin = prices[0]; for (int i = 1; i < prices.size(); i++) { if (prices[i] < preMin) preMin = prices[i]; profit = max(profit, prices[i] - preMin); } return profit; }
Best time to buy and stock Stock II
Unlimited operation: When ==> current price> purchase price, sell
The Code is as follows:
int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; int profit = 0; int buy = prices[0]; for (int i = 1; i < prices.size(); i++) { if (buy < prices[i]) profit += prices[i] - buy; buy = prices[i]; } return profit; }
Best time to buy and buy stock III
Only two operations can be performed:
The two operations cannot overlap and can be divided into two parts: 0 .. I maximum profit FST and I .. n-1 maximum profit SND
The Code is as follows:
int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; int size = prices.size(); vector<int> fst(size); vector<int> snd(size); int preMin = prices[0]; for (int i = 1; i < size; i++) { if (preMin > prices[i]) preMin = prices[i]; fst[i] = max(fst[i - 1], prices[i] - preMin); } int profit = fst[size - 1]; int postMax = prices[size - 1]; for (int i = size - 2; i >= 0; i--) { if (postMax < prices[i]) postMax = prices[i]; snd[i] = max(snd[i + 1], postMax - prices[i]); //update profit profit = max(profit, snd[i] + fst[i]); } return profit; }
Best time to buy and keep stock I, II, III [leetcode]