The Maximum Product Subarray problem requires finding the contiguous subarray that has the largest product.
For example:
Input:
[2, 3, -2, 4]
Output:
6
The subarray [2, 3] gives the maximum product.
2 × 3 = 6
Given an integer array nums, find a contiguous non-empty subarray that has the largest product and return the product.
- Finds the maximum product
- Handles positive and negative numbers
- Handles zero values
- Uses a single traversal
- Efficient solution
The program keeps track of two values:
currentMaxstores the largest product ending at the current position.currentMinstores the smallest product ending at the current position.
The minimum value is important because multiplying a negative number by a negative value can produce a large positive value.
When the current number is negative, currentMax and currentMin are swapped before updating them.
The maximum product found during the traversal is stored in maxProduct.
- Arrays
- Loops
- Conditional statements
- Methods
- Mathematical operations
The program uses an integer array to store the input values.
Finds and returns the maximum product of a contiguous subarray.
Creates the sample input, calls maxProduct(), and displays the result.
Start
↓
Read array
↓
Initialize current maximum
↓
Initialize current minimum
↓
Traverse array
↓
Check for negative value
↓
Swap maximum and minimum if needed
↓
Update current maximum
↓
Update current minimum
↓
Update maximum product
↓
Return result
↓
End
nums = [2, 3, -2, 4]
Maximum Product: 6
O(n)
The array is traversed once.
O(1)
Only a few variables are used.
This problem teaches how to handle negative numbers by tracking both the maximum and minimum products during array traversal.
Arrays/MaximumProductSubarray.java
Maximum-Product-Subarray/
├── README.md
└── Arrays/
└── MaximumProductSubarray.java
V.Harini