Problem Description
Given an integer array nums, find a contiguous subarray within the array (containing at least one number) which has the largest product, and return that product.
Key Insights
- Maintain both the maximum and minimum product at the current index because a negative number can swap the max and min.
- A subarray must be contiguous.
- Use dynamic programming to update both the maximum product and the minimum product ending at each index.
- Resetting the product in case of a zero is crucial since the product becomes 0.
Space and Time Complexity
Time Complexity: O(n) – The solution iterates through the array once. Space Complexity: O(1) – Constant space is used for tracking products.
Solution
The solution uses an iterative dynamic programming approach. At each index, compute the maximum product (maxEndingHere) and minimum product (minEndingHere) ending at that index. If the current element is negative, swap these two values, because multiplying a negative with a minimum product (possibly negative) might yield a larger product. After processing each element, update the global maximum. This method handles edge cases like zeros and negatives efficiently with constant additional space.