Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the maximum product with the first element of the array.
DSA Python
def max_product_subarray(nums): max_prod = [1] return max_prod
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing max_prod to 0 or 1 which may be incorrect if the first element is negative or less than 1.
✗ Incorrect
We start by setting max_prod to the first element because the maximum product subarray must include at least one element.
2fill in blank
mediumComplete the code to iterate through the array starting from the second element.
DSA Python
for i in [1](1, len(nums)): pass
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using list or enumerate which do not directly generate index ranges.
Starting loop from 0 instead of 1.
✗ Incorrect
We use range(1, len(nums)) to loop through the array starting from index 1.
3fill in blank
hardFix the error in updating the current maximum product by choosing the correct function to get the maximum.
DSA Python
curr_max = max(nums[i], curr_max * nums[i], [1] * nums[i])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using curr_max instead of curr_min, missing cases where negative times negative is positive.
✗ Incorrect
We use curr_min because multiplying a negative minimum product by a negative number can become a new maximum.
4fill in blank
hardFill both blanks to update current minimum product and maximum product so far.
DSA Python
curr_min = min(nums[i], [1] * nums[i], [2] * nums[i]) max_prod = max(max_prod, curr_max)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_prod or nums[i] incorrectly in the min function.
Not updating max_prod after curr_max changes.
✗ Incorrect
curr_min updates by considering nums[i], curr_min * nums[i], and curr_max * nums[i]. max_prod updates with the maximum found so far.
5fill in blank
hardFill all three blanks to swap current max and min when nums[i] is negative.
DSA Python
if nums[i] < 0: [1], [2] = [3], curr_max
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not swapping or swapping incorrectly causing wrong max/min tracking.
✗ Incorrect
When nums[i] is negative, we swap curr_max and curr_min to correctly track max and min products.