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.
Analyse:dp[i] = max (dp[i-1], prices[i]-lowest[0,..., i-1]).
Runtime:8ms.
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 Const intn =prices.size ();5 if(n = =0)return 0;6 7 intDp[n] = {0};8 intlowest = prices[0];9 for(inti =1; I < prices.size (); i++){TenDp[i] = max (Dp[i-1], Prices[i]-lowest); OneLowest =min (lowest, prices[i]); A } - returnDp[n-1]; - } the};
Or
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 if(Prices.size () <=1)return 0;5 6 intresult =0, pre =0;7 intlowest = prices[0];8 for(inti =1; I < prices.size (); i++){9result = Max (PRE, prices[i]-lowest);TenLowest =min (lowest, prices[i]); OnePre =result; A } - returnresult; - } the};
best time to Buy and Sell Stock