Example: Maximum Product Subarray - rFronteddu/general_wiki GitHub Wiki

Given an integer array nums, find a subarray that has the largest product, and return the product.

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        double maxP = nums[0];
        double minP = nums[0];
        double result = nums[0];

        for (int i = 1; i < nums.length; i++) {
            if(nums[i] == 0 {
                // current max and min will be 0 so the interval is finished
                maxP = 0;
                minP = 0;               
                result = Math.max(result, 0);
            } else {
                double temp = maxP;
                maxP = Math.max (nums[i], Math.max(nums[i] * maxP , nums[i] * minP));
                minP = Math.min (nums[i], Math.min(nums[i] * temp, nums[i] * minP));
                result = Math.max(result, maxProduct);
            }
        }

        return (int)result;
    }
}