Share Accepted DP JAVA O(n) Solution


  • 6
    C
    public class Solution {
        public int maxProduct(int[] nums) {
            int n = nums.length;
            int[] maxProduct = new int[n];
            int[] minProduct = new int[n];
            maxProduct[0] = nums[0];
            minProduct[0] = nums[0];
            for (int i = 1; i < n; i++) {
               int[] temp = new int[3];
               temp[0] = nums[i];
               temp[1] = nums[i] * maxProduct[i - 1];
               temp[2] = nums[i] * minProduct[i - 1];
               Arrays.sort(temp);
               minProduct[i] = temp[0];
               maxProduct[i] = temp[2];
            }
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                if (maxProduct[i] > max) {
                    max = maxProduct[i];
                }
            }
            return max;
        }
    }

  • 0
    M

    Are there any tips on how to approach DP solutions? It's my biggest weakness...


Log in to reply
 

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