Maximum Product Subarray in Python and Java
In this tutorial, we will learn LeetCode #152: Maximum Product Subarray in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Maximum Product Subarray Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use track max and min product because it gives a clean and optimized solution.
Example input: nums = [2, -5, -3, 4] Expected result: Output: 120 Explanation: The subarray [2, -5, -3, 4] gives 120.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: nums = [2, -5, -3, 4] Approach: track max and min product We update variables step by step until we reach: Output: 120
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why track max and min product is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. nums = [2, -5, -3, 4] We will solve it using track max and min product. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: 120 Why? The subarray [2, -5, -3, 4] gives 120.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: 120
Example 1
Input: nums = [2, -5, -3, 4] Output: Output: 120 Explanation: The subarray [2, -5, -3, 4] gives 120.
Example 2
Input: nums = [-2, 3, -4, 5] Output: 120 Explanation: The subarray [3, -4, 5] is not best; [-2, 3, -4, 5] gives 120.
Python Code
Here is the complete Python solution for LeetCode #152.
class MaximumProductSubarrayFinder:
def max_product(self, nums):
best = nums[0]
current_max = nums[0]
current_min = nums[0]
for num in nums[1:]:
if num < 0:
current_max, current_min = current_min, current_max
current_max = max(num, current_max * num)
current_min = min(num, current_min * num)
best = max(best, current_max)
return best
finder = MaximumProductSubarrayFinder()
print(finder.max_product([2, -5, -3, 4])) # Output: 120
print(finder.max_product([-2, 0, -1])) # Output: 0Java Code
Here is the complete Java solution for LeetCode #152.
class MaximumProductSubarrayFinder {
public int maxProduct(int[] nums) {
int best = nums[0];
int currentMax = nums[0];
int currentMin = nums[0];
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
if (num < 0) {
int temp = currentMax;
currentMax = currentMin;
currentMin = temp;
}
currentMax = Math.max(num, currentMax * num);
currentMin = Math.min(num, currentMin * num);
best = Math.max(best, currentMax);
}
return best;
}
public static void main(String[] args) {
MaximumProductSubarrayFinder finder = new MaximumProductSubarrayFinder();
System.out.println(finder.maxProduct(new int[] {2, -5, -3, 4})); // Output: 120
System.out.println(finder.maxProduct(new int[] {-2, 0, -1})); // Output: 0
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(1)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #152: Maximum Product Subarray becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.