Leetcode-best time to Buy and Sell Stock i&&ii

Source: Internet
Author: User

First: Test instructions is the stock price of a stock in an array. The first I is the price of the first day. The most profitable. Allowed to buy and sell once

The problem is to ask for the maximum difference. You can record the minimum value and then, based on the minimum value, find the current maximum difference.

 Public classSolution { Public intMaxprofit (int[] prices) {        if(prices.length==0| | Prices.length==1)        {            return0; }        intLow=prices[0],ans=0;  for(inti=1;i<prices.length;i++)        {            if(Low>prices[i]) low=Prices[i]; Record minimum valueElse            {                if(prices[i]-low>ans) {ans= prices[i]-Low ; }            }        }        returnans; }}

Second: Test instructions allows multiple transactions on the basis of the first question. But you must buy and sell, not buy or sell continuously.

The problem is to ask for the sum of all the difference values. You can imagine a stock price as a line chart. Adding the difference of all ascending segments is the result.

 Public classSolution { Public intMaxprofit (int[] prices) {        if(prices.length==0| | Prices.length==1)        {            return0; }        intLow = Prices[0]; intHigh = 0; intsum = 0;  for(inti = 1;i<prices.length;i++)        {            if(low>prices[i])//If the current stock price is below the minimum value, low suction=Prices[i]; }            Else            {                if((i<prices.length-1) && (prices[i+1]>Prices[i])) If the subsequent value is larger than the current value (still in the ascending phase) {Continue; }                else//If it is currently a peak, sell the stock{sum= sum+prices[i]-Low ; Low=Prices[i]; }                            }        }        returnsum; }}

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