JAVA AC answer. Dynamic Programming, two arrays.


  • 0
    H

    Keep two dp arrays. One for recording the current maximum, one for recording the current minimum.

    public class Solution {
     public int maxProduct(int[] nums) {
        int[] dp = new int[nums.length+1];
        int[] ng = new int[nums.length+1];
        dp[0] = 1;
        ng[0] = 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) dp[i+1] = 0;
            else if (nums[i]>=0) {
                dp[i+1] = Math.max(nums[i], dp[i]*nums[i]);
                ng[i+1] = Math.min(nums[i], ng[i]*nums[i]);
            } else {
                dp[i+1] = Math.max(nums[i], nums[i]*ng[i]);
                ng[i+1] = Math.min(nums[i], nums[i]*dp[i]);
            }
        }
    
        int max = Integer.MIN_VALUE;
        for (int i = 1; i<dp.length; i++) {
            max = Math.max(max, dp[i]);
        }
        return max;
    }
    

    }


Log in to reply
 

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