Ideas :
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.
code : OJ Test code runtime:111 ms
1 classSolution:2 #@param prices, a list of integers3 #@return An integer4 defMaxprofit (Self, prices):5 #None case or one element case6 ifPrices isNoneorLen (Prices) <2 :7 return08 #DP9Min_buy =0TenMax_profit =0 One forIinchRange (1, Len (Prices)): A ifprices[i]<Prices[min_buy]: -Min_buy =I -Max_profit = Max (prices[i]-prices[min_buy],max_profit) the returnMax_profit
Ideas :
A typical dynamic programming topic.
It is similar to this problem (http://www.cnblogs.com/xbf9xbf/p/4240510.html) to find the minimum subset.
Personally, the essence of this type of topic is " at each step, we maintain two variables, one is the global optimal, that is, to the current element so that the optimal solution is that a local optimal, that must contain the current element of the optimal solution ."
For this problem, there is a small stem need to figure out: if Prices[i] is the smallest value so far, then prices[i]-prices[min_buy] is not equal to 0?
Notice that the rules for dynamic planning are reviewed: Be sure to include the optimal solution for the current element. Since the current element is already the minimum value of history, it is not the best solution to include the current element, is it not himself minus himself?
Maintain a max_profit (maximum profit), a min_buy (historical lowest point).
1. If the current prices[i] is less than prices[min_buy], update the min_buy.
2. Take Prices[i]-prices[min_buy] and the larger one in Max_profit, as the value of Max_profit.
Finally, return to Max_profit.
Leetcode "best time to Buy and Sell Stock" Python implementation