My java solution


  • 0
    C
       public class Solution {
       public int maxProduct(int[] nums) {
        
    	if(nums.length == 1)
    		return nums[0];
    	
    	//define two caches to store min and max 
    	int[] resMAX = new int[nums.length];
    	int[] resMIN = new int[nums.length];
    	
    	resMAX[0] = nums[0];
    	resMIN[0] = nums[0];
    	
    	int maxV = nums[0];
    	int tmp =0;
    	
    	for(int i=1;i<nums.length;i++)
    	{
    		if(nums[i] == 0)
    		{
    			resMAX[i] = 1;
    			resMIN[i] = 1;
    		}
    		else
    		{
    			resMAX[i]=max(max(resMAX[i-1]*nums[i],resMIN[i-1]*nums[i]),nums[i]);
    			resMIN[i]=min(min(resMAX[i-1]*nums[i],resMIN[i-1]*nums[i]),nums[i]);
    			tmp=max(resMAX[i],resMIN[i]);
    		}
    		maxV=maxV>tmp?maxV:tmp;
    	}
    	return maxV;
    }
    
    
    private int max(int i, int j) {
    	// TODO Auto-generated method stub
    	return i>j?i:j;
    }
    
    private int min(int i, int j) {
    	// TODO Auto-generated method stub
    	return i>j?j:i;
    }
    

    }


Log in to reply
 

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