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.
Example 1:

 Input: [7, 1, 5, 3, 6, 4]
 Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:

 Input: [7, 6, 4, 3, 1]
 Output: 0

In this case, no transaction is done, i.e. max profit = 0.

这道题一开始做出了TLE,后来虽然AC了但是看detail发现速度也是慢得可以,说明O(N2)的方法是暴力法。暴力法的思路就是找到数组里的最大差,而且必须是数组后面的元素减去数组前面的元素,于是就需要2个for循环来遍历,维系一个maxDiff来更新;

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0){
            return 0;
        }    
        int maxDiff = 0;
        for (int i = 0; i < prices.length; i++){
            for (int j = i + 1; j < prices.length; j++){
                if (prices[j] > prices[i]){
                    int diff = prices[j] - prices[i];
                    if (diff > maxDiff){
                        maxDiff = diff;
                    }
                }
            }
        }
        return maxDiff;
    }
}

实际上本题可以轻松优化到O(N), 思路是最多利润 = 最高卖价 - 最低买价, 所以一开始我们维持一个min最低买价和一个最大利润maxDiff, 遍历后面的元素,如果比min更小就更新min,说明可以以更低的价格买入;如果比min高就更新maxDiff = Math.max(prices[i] - min, maxDiff)来更新最大利润.

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0){
            return 0;
        }    
        int min = prices[0];
        int maxDiff = 0;
        for (int i = 1; i < prices.length; i++){
            if (prices[i] < min){
                min = prices[i];
            } else {
                maxDiff = Math.max(prices[i] - min, maxDiff);
            }
        }
        return maxDiff;
    }
}

你可能感兴趣的:(121. Best Time to Buy and Sell Stock)