Simple Java Solution DP:)


  • 0
    S
    public class Solution {
        
        public int maxProfit(int[] prices) {
            if(prices == null || prices.length == 0) {
                return 0;
            }
            int maxProfit = 0;
            int minSoFar = prices[0];
            for(int i = 1;i<prices.length; i++) {
               maxProfit = prices[i] - minSoFar > maxProfit ? prices[i] - minSoFar : maxProfit;
               minSoFar = minSoFar > prices[i] ? prices[i] : minSoFar;
            }
            
            return maxProfit;
        }
    }

Log in to reply
 

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