# Simple Java code

• 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;
}
}``````

• You are right. Thanks for pointing out my mistake.

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

• no need to do the * twice

• beautiful code

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

• This is the most elegant 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;
}
}
``````

• This post is deleted!

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