Maximum Product Subarray | Brute Force → Optimal (Prefix/Suffix) | Java, C++, Python

Published: 13 March 2026
on channel: RisingBrain
5,227
206

In this video, we solve the Maximum Product Subarray problem step by step starting from the brute force approach and then moving to the optimal solution using the prefix and suffix product concept.

First, we understand the basic idea of generating all possible subarrays and calculating their product to find the maximum one. Then we discuss why this brute force approach is inefficient for large inputs. After that, we move to the key observation that negative numbers can flip the sign of the product and zeros can break the subarray, which makes this problem tricky.

To solve this efficiently, we use the prefix and suffix traversal technique, where we compute the running product from left to right and right to left. This helps us correctly handle negative numbers and reset the product whenever we encounter a zero.

In this video we cover:
Brute force approach and intuition
Why checking every subarray is inefficient
Key observation about negative numbers and zeros
Prefix product and suffix product concept
How scanning the array from both directions helps
Clean implementation in C++, Java, and Python

Time and Space Complexity:

Brute Force Approach
Time Complexity: O(n²)
Space Complexity: O(1)

Optimal Approach (Prefix + Suffix Product)
Time Complexity: O(n)
Space Complexity: O(1)

This problem is a very popular coding interview question and helps build strong intuition for handling arrays with negative numbers and product-based calculations.

Rising Brain (DSA Sheet) - https://www.risingbrain.org/sheet

Connect with me here:

Linkedin -   / anjalikumari22  
Instagram -   / rbanjali.codes  
Twitter - https://x.com/anjali1kumari?s=21


On this page of the site you can watch the video online Maximum Product Subarray | Brute Force → Optimal (Prefix/Suffix) | Java, C++, Python with a duration of hours minute second in good quality, which was uploaded by the user RisingBrain 13 March 2026, share the link with friends and acquaintances, this video has already been watched 5,227 times on youtube and it was liked by 206 viewers. Enjoy your viewing!