Leetcode OJ 121. best time to Buy and Sell Stock

Source: Internet
Author: User

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.

Ideas

I know that if you want to get a profit, the price sold must be higher than the buy price, and the date of sale is greater than the date of the purchase. So we buy at the lowest time and sell at the highest time. From day one, the first day of the price is set to the current lowest price, if the price of the next day is higher than the lowest price, we record the price difference at this time, if the profit is greater than the previous maximum profit then set it to the current maximum profit, and then the subscript moves backwards. If one day the price is lower than the current minimum price, we set the current price to the lowest price, and then continue the process until the end of the array is traversed. This process actually divides the array into a section, and the beginning of each paragraph is the lowest value within the range. For example: [2,24,4,1,3,7] The red section of 2 is the minimum value, and 24 is the maximum value. The Green section 1 is the minimum value, and 7 is the maximum value.

The code is as follows:

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         intMin = 0;4         intMP = 0;5 6          for(inti = 1; i < prices.length; i++) {7             if(Prices[min] > prices[i]) min =i;8             ElseMP = Math.max (MP, Prices[i)-prices[min]);9         }Ten  One         returnMP; A     } -}

Leetcode OJ 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.