Simple Java code


  • 79
    C

    Loop through the array, each time remember the max and min value for the previous product, the most important thing is to update the max and min value: we have to compare among max * A[i], min * A[i] as well as A[i], since this is product, a negative * negative could be positive.

    public class Solution {
        public int maxProduct(int[] A) {
            if (A == null || A.length == 0) {
                return 0;
            }
            int max = A[0], min = A[0], result = A[0];
            for (int i = 1; i < A.length; i++) {
                int temp = max;
                max = Math.max(Math.max(max * A[i], min * A[i]), A[i]);
                min = Math.min(Math.min(temp * A[i], min * A[i]), A[i]);
                if (max > result) {
                    result = max;
                }
            }
            return result;
        }
    }

  • 0
    E

    You are right. Thanks for pointing out my mistake.


  • 0
    H

    you missed a "," between 6 and -3, if you add it you can get the correct answer


  • 0
    G

    no need to do the * twice


  • 0
    Z

    beautiful code


  • 0
    P

    why there is sometimes time limit exceeded error? I haven't changed the solution and the error disappears......


  • 0
    S

    This is the most elegant answer ;)


  • 1

    share my answer

    public class Solution {
        public int maxProduct(int[] nums) {
            if (nums.length == 0) return 0;
            
            int res = nums[0];
            int positive = 1;
            int negative = 1;
            
            for (int i = 0; i < nums.length; i++) {
                int x = nums[i];
                if (x >= 0) {
                    positive = Math.max(positive * x, x);
                    negative = negative * x;
                } else {
                    int tmp = negative;
                    negative = Math.min(positive * x, x);
                    positive = tmp * x;
                }
                res = Math.max(res,positive);
                res = Math.max(res,negative);
            }
            return res;
        }
    }
    

  • 0
    X
    This post is deleted!

Log in to reply
 

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