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

Source: Internet
Author: User

title :

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).

code : OJ Test via runtime:71 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         #DP9buy =0TenSell =0 OneProfit =0 A          forIinchRange (len (prices)-1): -             ifPrices[i]<=prices[i+1]: -Sell = i+1 the             Else: -Profit = Profit + prices[sell]-Prices[buy] -buy = i+1 -Sell = i+1 +         returnProfit+max (0,prices[sell]-prices[buy])

Ideas :

Using greedy algorithm.

The logic of the code is clear: Find the longest rise interval, the lowest sell the highest buy can, and then find the next rise interval; when exiting the loop, pay attention to the last ascending or descending interval.

For loop:

1. If the part is to keep looking for greater room for rise, found the sell will be placed in a more profitable selling point.

2. Else part of the deal is the situation of price decline, buy and sell need to follow up, so that the same price to ensure the same purchase, do not lose money

There is a stem: After the code AC, I review found if and else inside have sell=i+1 this statement, then since whether the if or else have to execute sell=i+1, why do you have to carry out in each statement? So there is the following code ( this part of the code is the error example ): The result is an error.

            Sell = i+1            if prices[i]>prices[i+1]:                = profit + prices[sell]-prices[buy]                = i+1

This is a thought trap: Yes, it does execute the SELL=I+1 statement in the IF and else, but the logical order of the statement execution is different. Note that if the condition is prices[i]>prices[i+1], sell=i+1 is executed after the profit statement. Then it dawned and changed to the following code:

OJ Test via runtime:67 ms

classSolution:#@param prices, a list of integers    #@return An integer    defMaxprofit (Self, prices):#None case or one element case        ifPrices isNoneorLen (Prices) <2 :            return0#DPbuy =0 Sell=0 Profit=0 forIinchRange (len (prices)-1):            ifPrices[i]>prices[i+1]: Profit= Profit + prices[sell]-prices[buy] Buy= I+1Sell= I+1returnProfit+max (0,prices[sell]-prices[buy])

So the logic of the code is more concise, can be explained as follows: As long as the next two days, the day after a higher than the previous one can buy high sales to generate profits.

The second, more concise code, seems to be the answer that more people on the Web are listing. A simple solution can also be performed by a general solution.

Leetcode "best time to Buy and Sell Stock II" 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.