题目详情

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;
    }

soleil阿璐
350 声望45 粉丝

stay real ~