Bird
Raised Fist0
DSA Goprogramming

Maximum Product Subarray in DSA Go

Choose your learning style10 modes available
Mental Model
We want to find the largest product of a continuous part of the list. Because negative numbers can flip signs, we keep track of both the biggest and smallest products so far.
Analogy: Imagine walking on a path where stepping on a slippery stone (negative number) can flip your direction. To know how far you can go forward, you remember both your best forward and backward steps.
Array: [2] -> [-3] -> [4] -> [-1] -> [0] -> [5]
Tracking maxProd and minProd at each step
Dry Run Walkthrough
Input: array: [2, -3, 4, -1, 0, 5]
Goal: Find the maximum product of any continuous subarray
Step 1: Start with first element as maxProd=2, minProd=2, result=2
maxProd=2, minProd=2, result=2
Why: Initialize tracking with first element
Step 2: Process -3: calculate candidates (2*-3=-6, -3, 2*-3=-6), update maxProd and minProd
maxProd=-3, minProd=-6, result=2
Why: Negative flips max and min, so track both
Step 3: Process 4: candidates (-3*4=-12, 4, -6*4=-24), update maxProd=4, minProd=-24, result=4
maxProd=4, minProd=-24, result=4
Why: Positive number updates max and min accordingly
Step 4: Process -1: candidates (4*-1=-4, -1, -24*-1=24), update maxProd=24, minProd=-4, result=24
maxProd=24, minProd=-4, result=24
Why: Negative flips max and min again, maxProd increases
Step 5: Process 0: candidates (24*0=0, 0, -4*0=0), update maxProd=0, minProd=0, result=24
maxProd=0, minProd=0, result=24
Why: Zero resets products, but result keeps max found
Step 6: Process 5: candidates (0*5=0, 5, 0*5=0), update maxProd=5, minProd=0, result=24
maxProd=5, minProd=0, result=24
Why: Positive number updates maxProd, result remains max
Result:
Maximum product subarray is 24
Annotated Code
DSA Go
package main

import (
	"fmt"
)

func maxProduct(nums []int) int {
	if len(nums) == 0 {
		return 0
	}
	maxProd, minProd, result := nums[0], nums[0], nums[0]
	for i := 1; i < len(nums); i++ {
		curr := nums[i]
		candidates := []int{curr, maxProd * curr, minProd * curr}
		maxTemp := candidates[0]
		minTemp := candidates[0]
		for _, val := range candidates {
			if val > maxTemp {
				maxTemp = val
			}
			if val < minTemp {
				minTemp = val
			}
		}
		maxProd = maxTemp
		minProd = minTemp
		if maxProd > result {
			result = maxProd
		}
	}
	return result
}

func main() {
	arr := []int{2, -3, 4, -1, 0, 5}
	fmt.Println(maxProduct(arr))
}
maxProd, minProd, result := nums[0], nums[0], nums[0]
Initialize max and min products and result with first element
for i := 1; i < len(nums); i++ {
Traverse array from second element
candidates := []int{curr, maxProd * curr, minProd * curr}
Calculate possible products including current element
for _, val := range candidates { if val > maxTemp { maxTemp = val } if val < minTemp { minTemp = val } }
Update maxProd and minProd by checking all candidates
if maxProd > result { result = maxProd }
Update result if current maxProd is greater
OutputSuccess
24
Complexity Analysis
Time: O(n) because we scan the array once, updating max and min products at each step
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Naive approach tries all subarrays with O(n^2) or O(n^3) time, which is much slower
Edge Cases
empty array
returns 0 as no subarray exists
DSA Go
if len(nums) == 0 { return 0 }
array with one element
returns that element as max product
DSA Go
maxProd, minProd, result := nums[0], nums[0], nums[0]
array with zeros
resets max and min products to zero, but result keeps max found so far
DSA Go
candidates := []int{curr, maxProd * curr, minProd * curr}
When to Use This Pattern
When you need the maximum product of a continuous subarray and the array has negative numbers, use the max/min tracking pattern to handle sign flips.
Common Mistakes
Mistake: Only tracking maximum product without minimum product causes wrong results with negatives
Fix: Track both max and min products at each step to handle sign flips
Summary
Finds the maximum product of any continuous subarray in an array.
Use when array contains positive, negative, and zero values and you want max product subarray.
Keep track of both max and min products at each step because negatives can flip signs.

Practice

(1/5)
1. What does the "Maximum Product Subarray" problem ask you to find in an array of integers?
easy
A. The longest subarray with positive numbers
B. The contiguous subarray with the largest sum of its elements
C. The maximum single element in the array
D. The contiguous subarray with the largest product of its elements

Solution

  1. 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.
  2. Step 2: Differentiate from similar problems

    Unlike maximum sum subarray, here we multiply elements, so negative numbers and zeros affect the product differently.
  3. Final Answer:

    The contiguous subarray with the largest product of its elements -> Option D
  4. Quick Check:

    Maximum product subarray = contiguous subarray with max product [OK]
Hint: Look for contiguous elements with max multiplication [OK]
Common Mistakes:
  • Confusing product with sum
  • Ignoring negative numbers impact
  • Thinking about non-contiguous elements
2. Which of the following Go code snippets correctly initializes variables to track the maximum product subarray?
easy
A. maxProd, minProd, result := 1, 1, 1
B. maxProd, minProd, result := 0, 0, 0
C. maxProd, minProd, result := nums[0], nums[0], nums[0]
D. maxProd, minProd, result := -1, -1, -1

Solution

  1. Step 1: Understand initialization for max product subarray

    We start with the first element as initial max, min, and result to handle negative and positive values correctly.
  2. Step 2: Check each option's initialization

    maxProd, minProd, result := nums[0], nums[0], nums[0] uses nums[0] which is correct; others use fixed values that may not match array's first element.
  3. Final Answer:

    maxProd, minProd, result := nums[0], nums[0], nums[0] -> Option C
  4. Quick Check:

    Initialize with first element for correct tracking [OK]
Hint: Initialize with first element, not zero or one [OK]
Common Mistakes:
  • Initializing with zero causes wrong results if nums[0] is negative
  • Using 1 ignores negative or zero first elements
  • Not initializing minProd separately
3. What is the output of the following Go code for the input array nums := []int{2, 3, -2, 4}?
func maxProduct(nums []int) int {
    maxProd, minProd, result := nums[0], nums[0], nums[0]
    for i := 1; i < len(nums); i++ {
        if nums[i] < 0 {
            maxProd, minProd = minProd, maxProd
        }
        maxProd = max(nums[i], maxProd*nums[i])
        minProd = min(nums[i], minProd*nums[i])
        if maxProd > result {
            result = maxProd
        }
    }
    return result
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}
medium
A. 6
B. 4
C. -2
D. 8

Solution

  1. Step 1: Trace the loop and update maxProd, minProd, and result

    Start with maxProd=2, minProd=2, result=2 - i=1 (3): nums[i]=3 > 0, maxProd=max(3,2*3)=6, minProd=min(3,2*3)=3, result=6 - i=2 (-2): nums[i]<0, swap maxProd and minProd (maxProd=3, minProd=6), maxProd=max(-2,3*(-2))=-2, minProd=min(-2,6*(-2))=-12, result=6 - i=3 (4): nums[i]>0, maxProd=max(4,-2*4)=4, minProd=min(4,-12*4)=-48, result=6
  2. Step 2: Determine final result

    The maximum product found is 6 from subarray [2,3].
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Max product subarray = 6 [OK]
Hint: Swap max and min when negative number found [OK]
Common Mistakes:
  • Not swapping max and min on negative number
  • Confusing max and min updates
  • Ignoring update of result
4. Identify the bug in this Go code snippet for maximum product subarray:
func maxProduct(nums []int) int {
    maxProd, minProd, result := nums[0], nums[0], nums[0]
    for i := 1; i < len(nums); i++ {
        if nums[i] > 0 {
            maxProd = max(maxProd*nums[i], nums[i])
            minProd = min(minProd*nums[i], nums[i])
        } else {
            maxProd = max(minProd*nums[i], nums[i])
            minProd = min(maxProd*nums[i], nums[i])
        }
        if maxProd > result {
            result = maxProd
        }
    }
    return result
}
medium
A. Swapping maxProd and minProd is missing when nums[i] is negative
B. Initialization of maxProd, minProd, result is incorrect
C. Loop should start from i = 0 instead of 1
D. max and min functions are not defined

Solution

  1. Step 1: Analyze handling of negative numbers

    When nums[i] is negative, maxProd and minProd should be swapped before updating because multiplying by negative flips max and min.
  2. Step 2: Check the code's else block

    The code updates maxProd and minProd without swapping, causing incorrect results for negative numbers.
  3. Final Answer:

    Swapping maxProd and minProd is missing when nums[i] is negative -> Option A
  4. Quick Check:

    Swap max and min on negative input [OK]
Hint: Always swap max and min before multiplying negative number [OK]
Common Mistakes:
  • Forgetting to swap maxProd and minProd
  • Updating maxProd before minProd causing wrong minProd
  • Starting loop at wrong index
5. Given the array nums := []int{-1, -3, -10, 0, 60}, what is the maximum product subarray and its product?
hard
A. Subarray [-1, -3, -10] with product -30
B. Subarray [60] with product 60
C. Subarray [-3, -10, 0, 60] with product 0
D. Subarray [-10, 0, 60] with product 0

Solution

  1. Step 1: Evaluate products of possible subarrays

    Check subarrays: - [-1, -3, -10]: product = -1 * -3 * -10 = -30 - [60]: product = 60 - [-3, -10, 0, 60]: product = 0 (due to zero) - [-10, 0, 60]: product = 0 (due to zero)
  2. Step 2: Identify maximum product

    The highest product is 60 from subarray [60].
  3. Final Answer:

    Subarray [60] with product 60 -> Option B
  4. Quick Check:

    Max product = 60 from single element [OK]
Hint: Check single elements when zeros reset product [OK]
Common Mistakes:
  • Multiplying negative numbers without counting sign flips
  • Ignoring zero resets product
  • Assuming longer subarray always has max product
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard