Given an integer array nums, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Explanation: [2,3] has the largest product 6.
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
nums is guaranteed to fit in a 32-bit integer.The brute force approach is to generate all possible subarrays of the given array and calculate their products. Among all these products, we find the maximum product.
i to j.The product of elements in subarrays can be disrupted by negative numbers and zeros. A negative number turns a positive product into negative and vice versa, while zero resets it. Thus, we need to track both the maximum and minimum product subarrays because a negative product might become the largest if multiplied by another negative number.
Instead of recalculating products for every possible subarray, we maintain two potential products:
maxProductSoFar: Maximum product subarray ending at the current position.minProductSoFar: Minimum product subarray ending at the current position (to handle the case of two negative numbers resulting in a positive product).maxProductSoFar and minProductSoFar.maxProductSoFar and minProductSoFar.maxProductSoFar and minProductSoFar at each step.