【LeetCode】121. The best time to buy and sell stocks

topic

Given an array  prices whose th  i element  prices[i] represents the price of a given stock on the th  i day.

You can only choose  to buy the stock on one day  and   sell it on a different day in the future . Design an algorithm to calculate the maximum profit you can make.

Returns the maximum profit you can make from this trade. If you can't make any profit, return  0 .

Example 1:

Input: [7,1,5,3,6,4]
 Output: 5
 Explanation: buy on day 2 (stock price = 1), sell on day 5 (stock price = 6), Maximum profit = 6-1 = 5. 
     Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.

Example 2:

Input: prices = [7,6,4,3,1]
 Output: 0
 Explanation: In this case, no trades are completed, so the maximum profit is 0.

hint:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

answer

source code

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;

        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else if (prices[i] - minPrice > maxProfit) {
                maxProfit = prices[i] - minPrice;
            }
        }

        return maxProfit;
    }
}

Summarize

Try to refuse brute force cracking, traverse once, constantly update the lowest price and the maximum profit that can be obtained, and return the final maximum profit.

Guess you like

Origin blog.csdn.net/qq_57438473/article/details/131970205