122. Best time to Buy and Sell Stock II

Source: Internet
Author: User

Update Leetcode to solve Java answers on a regular basis.

Choose from the pick one approach.

As a result of the random series of problems, continue to do later versions.

Test instructions is given an array, the array represents the price of the item of the day, allowing multiple transactions (the premise of selling is to buy, buy the premise is to sell, that is, the body has no items to buy), ask the maximum benefit is how much.

The first way to analyze this is when we should buy and when we sell.

Imagine, when we buy goods, the next day if the price increases, we do not sell, to see whether the prices of the third days is lower than the next day; This step can be replaced by the following logic:

We bought the goods today, the next day the price increases, we need to make a third day of judgment; if we cut the price, we should sell it the day before and buy it the next morning (as above, if we just buy the next day, the price will be sold on the day of purchase, it will be equivalent to the first day of not buying). The following code can be used by the above analysis:

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         if(Prices.length = = 0)4             return0;5 6         intProfit = 0, Buyprice = prices[0];7         8          for(inti = 1; i < prices.length; i++){9             if(Prices[i] < prices[i-1]){TenProfit + = Prices[i-1]-Buyprice; OneBuyprice =Prices[i]; A             } -         } -         //Since the end of the loop there may not be an operation to perform a sell theProfit + = Prices[prices.length-1]-Buyprice; -          -         returnprofit; -     } +}

Similarly, the Python code is as follows:

1 classsolution (object):2     defMaxprofit (Self, prices):3         """4 : Type Prices:list[int]5 : Rtype:int6         """7         ifLen (prices) = =0:8             return0;9Profit =0TenBuyprice =Prices[0] OneLastprice =Prices[0] A          -          forPriceinchPrices: -             ifLastprice >Price : theProfit + = Lastprice-Buyprice -Buyprice = Price -                  -Lastprice = Price +          -Profit + = Prices[len (prices)-1]-Buyprice +          A         returnProfit

Of course, we can change a way of thinking, using the greedy method, as long as the next day than the first day of the price is higher, then we buy today, the next day to sell, to obtain the local optimal solution, in order to achieve the ultimate maximum benefit. This idea because there is no previous multi-day selling criteria (the third day is lower than the second day), after the loop does not need to replenish the code, the code is as follows:

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         intProfit = 0;4         5          for(inti = 1; i < prices.length; i++)6             if(Prices[i] > Prices[i-1])7Profit + = Prices[i]-prices[i-1];8 9         returnprofit;Ten     } One}

The corresponding Python code is as follows:

1 classsolution (object):2     defMaxprofit (Self, prices):3         """4 : Type Prices:list[int]5 : Rtype:int6         """7         ifLen (prices) = =0:8            return09Lastprice =Prices[0]TenProfit =0 One          forPriceinchPrices: A             ifPrice >Lastprice: -Profit + = Price-Lastprice -Lastprice = Price the         returnProfit

122. Best time to Buy and Sell Stock II

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.