121. Best time to Buy and Sell Stock

Source: Internet
Author: User

First, the topic

1, examining

2. Analysis

Give an array so that you have val1 to buy, and then sell with Val2, to get the most profit.

Second, the answer

1, Ideas:

Method One,

The minimum value that is recorded to the current position with the Traverse min;

Max records the maximum profit that is obtained when the price of the current array value is sold.

     Public intMaxprofit (int[] prices) {        if(Prices.length < 2)            return0; intMin = prices[0]; intMax = 0;  for(inti = 1; i < prices.length; i++) {            if(Prices[i]-min > 0 && prices[i]-min >max) {Max= Prices[i]-min; }            Else if(Prices[i] <min) min=Prices[i]; }        returnMax; }

  

Optimization:

The variable minprice directly records the current minimum value.

     Public int maxProfit3 (int[] prices) {                int minprice = integer.max_value, MAX = 0; c8/> for (int i = 1; i < prices.length; i++) {            = math.min (minprice, Price S[i]);             = Math.max (max, prices[i]- minprice);        }         return max;    }

Method Two,

Adopt "Kadane ' s algorithm.", that is, the idea of using the maximal and the continuous substring.

Curmax: The profit earned at the current price (if you don't make money, you don't sell).

①, if Curmax = 0, means that the current value is smaller than the value of the front;

②, Curmax > 0, i.e., Curmax = (price[i-1]-price[i-2] + price[i]-price[i-1]) = Price[i]-price[i-1]. That is, the current price is the maximum value, and the lowest value is subtracted from the front.

Max: The maximum profit in the total process.

     Public int maxProfit2 (int[] prices) {                int curmax = 0, max = 0;          for (int i = 1; i < prices.length; i++) {            = Math.max (0, Curmax + = prices[i]-prices[i-1]);             = Math.max (Curmax, max);        }         return max;    }

121. Best time to Buy and Sell Stock

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.