leetcode 121 Best Time to Buy and Sell Stock

題目詳情

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
這道題描述的意思就是,給定一個數組prices,裏面的第i個元素就是商品第i天的價格。咱們要選擇某天買入,某天賣出(賣出操做確定在買入操做以後)。求可能的最大利潤

題目給了兩個例子
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大利潤就是進價爲1,賣價爲6的時候,利潤爲5.
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
在這個案例中,進價一直高於售價,因此沒法成交,返回0。數組

理解

  • 這道題理解了實際上是比較簡單的。主要注意一下,先買入才能賣出、賣價必定要比買入價格高才能成交就能夠了。

解法

public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int minBuyPrice = 0;
        
        if(prices.length <= 1){
            return 0;
        }
        
        minBuyPrice = prices[0];
        
        for(int i=1;i<prices.length;i++){
            int curPrice = prices[i];
            if(curPrice < minBuyPrice){
                minBuyPrice = curPrice;
            }else if(curPrice - minBuyPrice > maxProfit){
                maxProfit = curPrice - minBuyPrice;
            }
        }
        
        return maxProfit;
    }
相關文章
相關標籤/搜索