Share O(1) space O(n) time Java DP Solution


  • 0
    M
        public int maxProfit(int[] prices) {
            if (prices == null || prices.length <= 1) return 0;
            int max = 0;
            int n = prices.length;
            int[] profit = new int[3];
            int funj = -prices[0];
            for (int i = 1; i < n; ++i) {
                profit[i % 3] = Math.max(profit[(i - 1) % 3], funj + prices[i]);
                funj = Math.max(funj, (i >= 2 ? profit[(i - 2) % 3] : 0) - prices[i]);
            }
            return profit[(n - 1) % 3];
        }
    

Log in to reply
 

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