Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Maximum Product Subarray
Dynamic Programming - Optimal Approach



Problem Statement

Given an array of integers (which may contain positive numbers, negative numbers, and zeros), your task is to find the maximum product that can be obtained from a contiguous subarray.

If the array is empty, the answer should be 0.

Examples

Input ArrayMaximum ProductDescription
[2, 3, -2, 4]6Subarray [2, 3] gives the max product 6
[-2, 0, -1]0Zero breaks product chains, so max product is 0
[-2, 3, -4]24Subarray [3, -4] gives 3 * -4 = -12, but [-2, 3, -4] gives 24
[0, 0, 0]0All elements are zero, so product is 0
[5]5Single element positive, product is the element itself
[-5]-5Single negative number, product is the element itself
[1, -2, -3, 4]24Subarray [-2, -3, 4] gives max product
[6, -3, -10, 0, 2]180Subarray [6, -3, -10] gives 180
[]0Empty array has no elements; product is 0

Solution

To find the maximum product subarray, we need to understand how multiplication behaves with different types of numbers. Unlike sum problems, multiplication is tricky because of negatives and zeros.

Key Observations

  • Multiplying a negative with another negative becomes positive.
  • Zero resets the product (anything multiplied by 0 becomes 0).
  • We are interested in the maximum product, which can be hidden between negative values or split by zeros.

How We Approach the Problem

We scan the array from left to right, and at each position, we maintain two values:

  • max_product: the maximum product ending at that index
  • min_product: the minimum product ending at that index (important for handling negatives)

If we encounter a negative number, we swap max and min because a large negative times a negative could become the new maximum.

If we encounter a zero, we reset both max and min to zero (or start fresh from the next element).

At every step, we update our final result with the highest max_product seen so far.

📦 Case-by-Case Explanation

  • All positives: The maximum product is the product of the whole array.
  • All negatives with even count: Product of the whole array will be positive and maximum.
  • All negatives with odd count: Exclude one negative (whichever gives max).
  • Zeros present: Treat zeros as split points; maximum product may lie in segments between them.
  • Single element array: That element is the maximum product.
  • Empty array: No product is possible, so return 0.

🎯 Final Thoughts

This is a classic example of using dynamic programming to track values at each step. The key trick is keeping both min and max products because negatives can flip roles. This approach ensures we always find the best subarray in O(n) time.

Visualization

Algorithm Steps

  1. Given an array arr of integers.
  2. Initialize three variables: max_product = arr[0], min_product = arr[0], and result = arr[0].
  3. Traverse the array from index 1:
  4. → If the current element is negative, swap max_product and min_product.
  5. → Update max_product as the maximum of current element and current element * max_product.
  6. → Update min_product as the minimum of current element and current element * min_product.
  7. → Update result as the maximum of result and max_product.
  8. Return result as the final maximum product subarray.

Code

Python
JavaScript
Java
C++
C
def max_product_subarray(arr):
    max_product = min_product = result = arr[0]

    for num in arr[1:]:
        if num < 0:
            max_product, min_product = min_product, max_product

        max_product = max(num, num * max_product)
        min_product = min(num, num * min_product)

        result = max(result, max_product)

    return result

# Sample Input
arr = [2, 3, -2, 4]
print("Maximum Product Subarray:", max_product_subarray(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)In the best case, the array contains only positive numbers, and a single pass through the array is sufficient to compute the result.
Average CaseO(n)The algorithm always traverses the entire array once to keep track of current maximum and minimum products due to possible negative values.
Average CaseO(n)Even if the array has many sign changes and zeros, the algorithm must still iterate over every element to track product variations.

Space Complexity

O(1)

Explanation: The solution uses only a constant number of variables (max_product, min_product, result), so the space used does not grow with input size.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M