Simple DP Java Solution w/ explanation


  • 0
    F

    Idea:

    • Iterate through in order, keeping track of the minimum stock price and the best deal so far
      • While also keeping track of the best deal so far.
      • A "deal" is computed as: current stock price - minimum stock price

    Solution:

        public int maxProfit(int[] prices) {
            if (prices.length == 0) return 0;
            
            int minStockPrice = prices[0];
            int bestDeal = 0;
            
            
            for (int i = 0; i < prices.length; i++) {
                minStockPrice = Math.min(prices[i], minStockPrice);
                bestDeal = Math.max(prices[i] - minStockPrice, bestDeal);
            }
            
            return bestDeal;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.