1. Title: best time toBuy and Sell Stock
Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
Solution:
int Maxprofit (vector<int>& prices) { if (prices.size () <=1) return 0; int minprice=prices[0]; int maxpro=0; for (int i=1; i<prices.size (); i++) { minprice=min (prices[i], minprice); Maxpro=max (MaxPro, Prices[i]-minprice); } return maxPro; }
2. Title:Best time to Buy and Sell Stock II
Say you has 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 could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).
int Maxprofit (vector<int>& prices) { int retprofit=0; for (int i=1; i<prices.size (); i++) { if (prices[i]>prices[i-1]) retprofit+=prices[i]-prices[i-1]; } return retprofit; }
3. Title: Best time toBuy and Sell Stock III
Say you has 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 are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Solution:
main idea: Check the current position left + right to trade one at a time, the sum of the maximum profit of
int Maxprofit (vector<int>& prices) { if (prices.size () <=1) return 0; Vector<int> Begin_end (prices.size (), 0); Vector<int> End_begin (prices.size (), 0); int minp=prices[0]; begin_end[0]=0; for (int i=1; i<prices.size (); i++) { minp=min (MINP, prices[i]); Begin_end[i]=max (PRICES[I]-MINP, begin_end[i-1]); } int Maxp=prices[prices.size ()-1]; End_begin[prices.size () -1]=0; for (int i=prices.size ()-2; i>=0; i--) { Maxp=max (MAXP, prices[i]); End_begin[i]=max (Maxp-prices[i], end_begin[i+1]); } int maxpro=begin_end[0]+end_begin[0]; for (int i=1; i<prices.size (); i++) { if (begin_end[i]+end_begin[i]>maxpro) Maxpro=begin_end[i]+end_ Begin[i]; } return maxPro; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
best time to Buy and Sell Stock