Maximum Product Subarray in DSA C - Time & Space Complexity
We want to understand how the time needed to find the maximum product subarray changes as the input array grows.
How does the number of steps grow when the array gets bigger?
Analyze the time complexity of the following code snippet.
int maxProduct(int* nums, int numsSize) {
int maxProd = nums[0], minProd = nums[0], result = nums[0];
for (int i = 1; i < numsSize; i++) {
if (nums[i] < 0) {
int temp = maxProd;
maxProd = minProd;
minProd = temp;
}
maxProd = (nums[i] > maxProd * nums[i]) ? nums[i] : maxProd * nums[i];
minProd = (nums[i] < minProd * nums[i]) ? nums[i] : minProd * nums[i];
if (maxProd > result) result = maxProd;
}
return result;
}
This code finds the maximum product of any contiguous subarray in the input array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through each element of the array once.
- How many times: The loop runs exactly once for each element, so n times where n is the array size.
As the array size grows, the number of steps grows directly in proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: Doubling the input size roughly doubles the work done.
Time Complexity: O(n)
This means the time to find the maximum product subarray grows linearly with the size of the input array.
[X] Wrong: "Because there are nested calculations, the time complexity must be quadratic O(n²)."
[OK] Correct: The code only loops once through the array; the calculations inside the loop are constant time, so the total time grows linearly, not quadratically.
Understanding this linear time solution shows you can handle tricky problems efficiently, a skill that helps in many real-world coding challenges.
"What if we used a nested loop to check every possible subarray product? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem and differentiate from similar problems
The problem asks for a contiguous part of the array where the product of all elements is the highest possible. Unlike maximum sum subarray, this problem focuses on product, which can be affected by negative numbers and zeros.Final Answer:
The contiguous subarray with the largest product of its elements -> Option DQuick Check:
Maximum product subarray = largest product subarray [OK]
- Confusing product with sum
- Ignoring negative numbers impact
- Thinking subarray can be non-contiguous
Solution
Step 1: Initialize maxProd and minProd properly and check alternatives
Both maxProd and minProd should start at 1 because multiplying by 1 does not change the product. Other initializations use zero (nullifies products), negative values, or leave variables uninitialized leading to incorrect calculations or undefined behavior.Final Answer:
int maxProd = 1, minProd = 1; -> Option AQuick Check:
Initialize maxProd and minProd to 1 [OK]
- Initializing maxProd or minProd to 0
- Not initializing both variables
- Using negative initial values
int arr[] = {2, 3, -2, 4};?
int maxProductSubarray(int* nums, int numsSize) {
int maxProd = nums[0], minProd = nums[0], result = nums[0];
for (int i = 1; i < numsSize; i++) {
if (nums[i] < 0) {
int temp = maxProd;
maxProd = minProd;
minProd = temp;
}
maxProd = (nums[i] > maxProd * nums[i]) ? nums[i] : maxProd * nums[i];
minProd = (nums[i] < minProd * nums[i]) ? nums[i] : minProd * nums[i];
if (maxProd > result) result = maxProd;
}
return result;
}
int main() {
int arr[] = {2, 3, -2, 4};
int size = sizeof(arr) / sizeof(arr[0]);
printf("%d", maxProductSubarray(arr, size));
return 0;
}Solution
Step 1: Trace the loop and determine final result
Start with maxProd=2, minProd=2, result=2. - i=1 (3): maxProd=max(3,2*3)=6, minProd=min(3,2*3)=3, result=6 - i=2 (-2): swap to maxProd=3, minProd=6; maxProd=max(-2,3*(-2))=-2, minProd=min(-2,6*(-2))=-12, result=6 - i=3 (4): maxProd=max(4,-2*4)=4, minProd=min(4,-12*4)=-48, result=6 The maximum product found is 6 from subarray [2,3].Final Answer:
6 -> Option BQuick Check:
Max product subarray = 6 [OK]
- Not swapping max and min on negative number
- Confusing max product with sum
- Incorrectly updating result
int maxProductSubarray(int* nums, int numsSize) {
int maxProd = 1, minProd = 1, result = nums[0];
for (int i = 0; i < numsSize; i++) {
if (nums[i] < 0) {
int temp = maxProd;
maxProd = minProd;
minProd = temp;
}
maxProd = (nums[i] > maxProd * nums[i]) ? nums[i] : maxProd * nums[i];
minProd = (nums[i] < minProd * nums[i]) ? nums[i] : minProd * nums[i];
if (maxProd > result) result = maxProd;
}
return result;
}Solution
Step 1: Check initialization and loop start; analyze other options
maxProd and minProd should start as nums[0] to correctly handle the first element. Loop should start from i=1 to avoid reprocessing first element. Removing swap breaks handling of negative numbers. Initializing result to 1 is incorrect if nums[0] is negative. Changing loop start without fixing initialization causes errors.Final Answer:
Initialize maxProd and minProd with nums[0] and start loop from i=1 -> Option AQuick Check:
Proper initialization and loop start fix bug [OK]
- Starting loop from 0 with maxProd=1
- Not swapping max and min on negative
- Wrong initialization of result
int arr[] = {-1, -3, -10, 0, 60};, what is the maximum product of any contiguous subarray?Solution
Step 1: Analyze subarrays and their products
Relevant products: [60]=60, [-3,-10]=30, [-1,-3]=3, [-1,-3,-10]=-30, [-10]=-10, subarrays crossing or including 0=0. No larger contiguous product exists (e.g. [-3,-10,60] skips 0, invalid).Final Answer:
60 -> Option CQuick Check:
Max product subarray = 60 [OK]
- Thinking non-contiguous subarrays like [-3,-10,60] are valid
- Choosing [-3,-10]=30 instead of 60
- Confusing zero as max product
Ready to prove it?
Pass the test and this pattern moves unknown
