Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

  • Time: O(n)
  • Space: O(1)
public int maxProduct(int[] nums) {
    int preMax = nums[0], preMin = nums[0], max = nums[0];
    for (int i = 1; i < nums.length; i++) {
        int tempMax = preMax;
        preMax = Math.max(nums[i], Math.max(preMin * nums[i], preMax * nums[i]));
        preMin = Math.min(nums[i], Math.min(preMin * nums[i], tempMax * nums[i]));
        max = Math.max(max, preMax);
    }
    return max;
}

results matching ""

    No results matching ""