📖 Scenario: Imagine you are analyzing daily sales growth rates of a product over a week. These growth rates can be positive (growth), negative (decline), or zero (no change). You want to find the period where the product's sales growth multiplied together is the highest.
🎯 Goal: Build a program that finds the maximum product of a contiguous subarray within a list of integers representing daily growth rates.
📋 What You'll Learn
Create a list called growth_rates with the exact values: [2, 3, -2, 4]
Create a variable called max_product initialized to the first element of growth_rates
Use a for loop with index i starting from 1 to iterate over growth_rates
Inside the loop, update variables to track the maximum and minimum products ending at the current index
Print the final value of max_product
💡 Why This Matters
🌍 Real World
This algorithm helps businesses analyze periods of growth or decline by finding the best continuous stretch of positive impact in sales or stock prices.
💼 Career
Understanding this problem is useful for roles in data analysis, financial modeling, and software engineering where time series data and optimization are common.
Progress0 / 4 steps
1
Create the growth rates list
Create a list called growth_rates with these exact values: [2, 3, -2, 4]
DSA Python
Hint
Use square brackets to create a list and separate values with commas.
2
Initialize max_product, min_product, and result
Create three variables called max_product, min_product, and result and set all of them to the first element of growth_rates
DSA Python
Hint
Set all three variables equal to the first element of the list using growth_rates[0].
3
Loop through growth_rates to find max product subarray
Use a for loop with variable i starting from 1 to iterate over growth_rates. Inside the loop, create a temporary variable temp_max to store the current max_product. Update max_product to the maximum of growth_rates[i], max_product * growth_rates[i], and min_product * growth_rates[i]. Update min_product to the minimum of growth_rates[i], temp_max * growth_rates[i], and min_product * growth_rates[i]. Update result to the maximum of result and max_product.
DSA Python
Hint
Remember to save the old max_product in a temporary variable before updating it.
4
Print the maximum product subarray result
Print the value of result to display the maximum product of a contiguous subarray.
DSA Python
Hint
Use print(result) to show the final answer.
Practice
(1/5)
1. What does the Maximum Product Subarray problem ask you to find in an integer array?
easy
A. The subarray with the smallest product of its elements
B. The contiguous subarray with the largest sum of its elements
C. The contiguous subarray with the largest product of its elements
D. The subarray with the largest difference between elements
Solution
Step 1: Understand the problem statement
The problem asks for a contiguous part of the array where the product of all elements is the highest possible.
Step 2: Compare options with problem goal
Only The contiguous subarray with the largest product of its elements matches the goal of finding the maximum product of a contiguous subarray.
Final Answer:
The contiguous subarray with the largest product of its elements -> Option C
Quick Check:
Maximum product subarray = largest product contiguous segment [OK]
Hint: Look for largest product, not sum or difference [OK]
Common Mistakes:
Confusing product with sum
Ignoring the contiguous subarray condition
Thinking about smallest product instead
2. Which of the following Python code snippets correctly initializes variables to track the maximum product subarray?
easy
A. max_prod = None; min_prod = None; result = None
B. max_prod = 0; min_prod = 0; result = 0
C. max_prod = float('inf'); min_prod = float('-inf'); result = 0
D. max_prod = nums[0]; min_prod = nums[0]; result = nums[0]
Solution
Step 1: Understand initialization for max and min products
We start with the first element as initial max, min, and result because the subarray must include at least one element.
Step 2: Check each option's correctness
max_prod = nums[0]; min_prod = nums[0]; result = nums[0] correctly initializes all three variables to the first element of the array, which is standard practice.
Final Answer:
max_prod = nums[0]; min_prod = nums[0]; result = nums[0] -> Option D
Quick Check:
Initialize with first element to track products [OK]
Hint: Initialize with first element, not zero or None [OK]
Common Mistakes:
Initializing with zero causes wrong results if array has negatives
Using None causes errors in multiplication
Using infinity values breaks logic
3. What is the output of the following code?
def maxProduct(nums):
max_prod = min_prod = result = nums[0]
for n in nums[1:]:
candidates = (n, max_prod * n, min_prod * n)
max_prod = max(candidates)
min_prod = min(candidates)
result = max(result, max_prod)
return result
print(maxProduct([2,3,-2,4]))
4. Find the error in this code snippet for maximum product subarray:
def maxProduct(nums):
max_prod = min_prod = result = 0
for n in nums:
temp_max = max_prod
max_prod = max(n, max_prod * n, min_prod * n)
min_prod = min(n, temp_max * n, min_prod * n)
result = max(result, max_prod)
return result
medium
A. Initializing max_prod, min_prod, and result to 0 instead of nums[0]
B. Using temp_max instead of max_prod directly
C. Not iterating from second element
D. Returning result instead of max_prod
Solution
Step 1: Check variable initialization
Initializing max_prod, min_prod, and result to 0 causes errors if all numbers are negative or first element is not zero.
Step 2: Compare with correct initialization
Correct approach initializes these variables to nums[0] to handle negative and positive values properly.
Final Answer:
Initializing max_prod, min_prod, and result to 0 instead of nums[0] -> Option A
Quick Check:
Initialize with first element, not zero [OK]
Hint: Always initialize with first element, not zero [OK]
Common Mistakes:
Starting max/min product at zero causes wrong results
Not handling negative numbers properly
Forgetting to update result each iteration
5. Given the array nums = [1, -2, -3, 0, 7, -8, -2], what is the maximum product of any contiguous subarray?