2ms DP solution


  • 0
    S
    public int maxProduct(int[] nums) {
            if (nums.length == 1) return nums[0];
    		
    	int max = 0, preP = 0, preN = 0;
    	for (int i = 0; i < nums.length; i++) {
    		int tempP = 0, tempN = 0;
    		if (nums[i] > 0){
    			if (preP == 0) tempP = nums[i];
    			else tempP = preP * nums[i];
    			if (preN != 0) tempN = preN * nums[i];
    		}else if (nums[i] < 0) {
    			if (preP == 0) tempN = nums[i];
    			else tempN = preP * nums[i];
    			if (preN != 0) tempP = preN * nums[i];
    			else tempP = 0;
    		}
    		preP = tempP;
    		preN = tempN;
    		max = Math.max(max, preP);
    	}
    	return max;
    }
    

Log in to reply
 

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