Leetcode "best time to Buy and Sell Stock" Python implementation

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.