POSTS

Leetcode 121 "Best Time to Buy and Sell Stock"

Title

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

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

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