Clicky

Leetcode 121 "Best Time to Buy and Sell Stock"

January 1, 2022

Title

(121. Best Time to Buy and Sell Stock)[https://leetcode.com/problems/best-time-to-buy-and-sell-stock/]

Result

Runtime: 6 ms, faster than 29.03% of Java online submissions for Best Time to Buy and Sell Stock. Memory Usage: 83.9 MB, less than 35.75% of Java online submissions for Best Time to Buy and Sell Stock.

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int buy = -1;
        int sell = -1;
        for(int i=0; i<prices.length; i++) {
            // if we never bought we buy
            if(buy == -1 
               // if the price today is lower then when we buy, its not worth
               // going futher based based on the previous buy price
               // buy here and continue...
               || prices[i] < prices[buy]) {
                buy = i;
                sell = -1;
                continue;
            } 
            // if we never sold we sell
            if (sell == -1 
                // if the price today is higher then when we previously sold
                // lets check the new max...
                || prices[i] > prices[sell]) {
                sell = i;
                if(prices[sell] - prices[buy] > max) {
                    max = prices[sell] - prices[buy];
                }
            }
        }
        return max;
    }
}

Result

Runtime: 2 ms, faster than 32.12% of Java online submissions for Best Time to Buy and Sell Stock.

Memory Usage: 39.9 MB, less than 22.47% of Java online submissions for Best Time to Buy and Sell Stock.

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        if(prices.length == 0)
            return 0;
        if(prices.length == 1)
            return 0;
        
        int indexMin = 0;
        int indexMax = 0;
        for(int i=1; i<prices.length; i++) {
            if (prices[i] < prices[i-1])
                continue;
            if (prices[i-1] < prices[indexMin]) {
                indexMin = i-1;
            }
            if (indexMin >= indexMax || 
                prices[i] >= prices[indexMax]) {
                    indexMax = i; 
            }
            if (indexMin < indexMax)
                max = Math.max(max, prices[indexMax] - prices[indexMin]);
        }
        return max;
    }
}

Result

Runtime: 369 ms, faster than 5.12% of Java online submissions for Best Time to Buy and Sell Stock.

Memory Usage: 41.1 MB, less than 18.52% of Java online submissions for Best Time to Buy and Sell Stock.

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i=0; i<prices.length; i++) {
            for(int j=i; j<prices.length; j++) {
                max = Math.max(max, prices[j] - prices[i]);
            }
        }
        return max;
    }
}