Back to Practice Dashboard
Python BasicsHard

Find maximum product sub-array

Learn how to solve the 'Find maximum product sub-array' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Hard

Write a function max_product_subarray(arr) that takes a list of integers arr and returns the maximum product of any contiguous subarray. A subarray must contain at least one element.

Constraints
  • 1 <= len(arr) <= 10^4
  • -10 <= arr[i] <= 10

Examples

Example 1
Input
arr = [2, 3, -2, 4]
Output
6
Explanation

The subarray [2, 3] has the maximum product: 2 * 3 = 6.

Example 2
Input
arr = [-2, 0, -1]
Output
0
Explanation

The subarray [0] gives the maximum product of 0, since all other products are negative or zero.

Example 3
Input
arr = [-2, -3, 4]
Output
24
Explanation

The entire array: (-2) * (-3) * 4 = 24? Wait, that's the subarray [-2,-3,4] = 24. Yes, two negatives multiply to positive.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor