LeetCode: Maximum Product Subarray (1ms)
Here is my solution to Maximum Product Subarray in LeetCode. It is interesting to work on these problems and see how my solution compares with others in the world.
public class Solution {
public int maxProduct(int[] nums) {
int max = 1;
int leftToRightMax = nums[0];
int rightToLeftMax = nums[0];
//Transverse from left to right keeping the max
for (int j = 0; j < nums.length ; j++) {
max = max * nums[j];
if (max > leftToRightMax) {
leftToRightMax = max;
}
if (max == 0) {
max = 1;
}
}
max = 1;
//Transverse from right to left keeping the max
for (int j = nums.length - 1; j >= 0 ; j--) {
max = max * nums[j];
if (max > rightToLeftMax) {
rightToLeftMax = max;
}
if (max == 0) {
max = 1;
}
}
max = Math.max(leftToRightMax, rightToLeftMax);
return max;
}
}