A entirely different way to tackle this issue. Fancy and cool. [You have to upvote me].


  • -1
    C

    The basic idea here is simple. For example: A,B,C,D,E,F,G,H,I,J,K. We have 11 numbers here.
    If the number of negative number is even, we output the product of all of the numbers. If the number of negative number is odd, for example (D G I), the maximum must be either product of A~H or E~K. If 0 is met, we reset all status flag.

    public int maxProduct(int[] nums) {
    	int result=Integer.MIN_VALUE,cur=0,cur1=Integer.MIN_VALUE;
    	boolean start=false;
    	for(int i=0;i<nums.length;i++){
    		if(nums[i]!=0){
    			cur=cur==0?nums[i]:cur*nums[i]; //track product of all numbers before last negative number
    			cur1=start==true?(cur1==Integer.MIN_VALUE?nums[i]:cur1*nums[i]):cur1; //track product of all numbers after first negative number
    			result=Math.max(result,Math.max(cur1, cur));
    			start=nums[i]<0?true:start;
    		}
    		else{
    			cur=0;
    			cur1=Integer.MIN_VALUE;
    			start=false;
    			result=Math.max(result,0);
    		}
    	}
    	return result;
    }

  • 0
    R

    Could not understand your code
    Would you mind explain more details ?


Log in to reply
 

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