Arrays January 13 ,2026

Maximum Product Subarray

Problem Statement

You are given an integer array arr.
Find the contiguous subarray (containing at least one number) which has the maximum product, and return that product.

Example 1

Input

arr = [2, 3, -2, 4]

Output

6

Explanation

Subarray [2, 3] gives maximum product = 6

Example 2

Input

arr = [-2, 0, -1]

Output

0

Why This Problem Is Important

  • Very frequently asked interview problem
  • Tests handling of negative numbers
  • Tests dynamic programming thinking
  • Edge cases with zero and sign flips
  • Appears in FAANG interviews

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n²)O(1)
Approach 2Prefix & Suffix ProductO(n)O(1)
Approach 3Kadane’s Variant (Optimal)O(n)O(1)

Approach 1: Brute Force

Idea

Calculate product of every possible subarray and track the maximum.

Algorithm

  1. Initialize maxProduct = -∞
  2. For each starting index i
  3. Multiply elements from i to j
  4. Update maxProduct

Time & Space Complexity

  • Time: O(n²)
  • Space: O(1)

Implementations

C

#include 
#include 

int main() {
    int arr[] = {2,3,-2,4};
    int n = 4;
    int maxProduct = INT_MIN;

    for(int i = 0; i < n; i++) {
        int prod = 1;
        for(int j = i; j < n; j++) {
            prod *= arr[j];
            if(prod > maxProduct)
                maxProduct = prod;
        }
    }

    printf("%d", maxProduct);
    return 0;
}

C++

#include 
#include 
using namespace std;

int main() {
    int arr[] = {2,3,-2,4};
    int n = 4;
    int maxProduct = INT_MIN;

    for(int i = 0; i < n; i++) {
        int prod = 1;
        for(int j = i; j < n; j++) {
            prod *= arr[j];
            maxProduct = max(maxProduct, prod);
        }
    }

    cout << maxProduct;
    return 0;
}

Java

public class MaxProductSubarray {
    public static void main(String[] args) {
        int[] arr = {2,3,-2,4};
        int maxProduct = Integer.MIN_VALUE;

        for(int i = 0; i < arr.length; i++) {
            int prod = 1;
            for(int j = i; j < arr.length; j++) {
                prod *= arr[j];
                maxProduct = Math.max(maxProduct, prod);
            }
        }

        System.out.print(maxProduct);
    }
}

Python

arr = [2,3,-2,4]
maxProduct = float('-inf')

for i in range(len(arr)):
    prod = 1
    for j in range(i, len(arr)):
        prod *= arr[j]
        maxProduct = max(maxProduct, prod)

print(maxProduct)

JavaScript

let arr = [2,3,-2,4];
let maxProduct = -Infinity;

for (let i = 0; i < arr.length; i++) {
    let prod = 1;
    for (let j = i; j < arr.length; j++) {
        prod *= arr[j];
        maxProduct = Math.max(maxProduct, prod);
    }
}

console.log(maxProduct);

Approach 2: Prefix & Suffix Product

Idea

Because negatives flip signs, compute product from left to right and right to left, resetting on zero.

Algorithm

  1. Initialize maxProduct, prefix = 1, suffix = 1
  2. Traverse array from left
    • prefix *= arr[i]
    • Update max
    • Reset prefix if zero
  3. Traverse from right
    • Same logic using suffix

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C++

#include 
#include 
using namespace std;

int main() {
    int arr[] = {2,3,-2,4};
    int n = 4;
    int maxProduct = INT_MIN;
    int prefix = 1, suffix = 1;

    for(int i = 0; i < n; i++) {
        prefix = (prefix == 0 ? 1 : prefix) * arr[i];
        suffix = (suffix == 0 ? 1 : suffix) * arr[n - i - 1];
        maxProduct = max(maxProduct, max(prefix, suffix));
    }

    cout << maxProduct;
    return 0;
}

Java

public class MaxProductSubarray {
    public static void main(String[] args) {
        int[] arr = {2,3,-2,4};
        int maxProduct = Integer.MIN_VALUE;
        int prefix = 1, suffix = 1;
        int n = arr.length;

        for(int i = 0; i < n; i++) {
            prefix = (prefix == 0 ? 1 : prefix) * arr[i];
            suffix = (suffix == 0 ? 1 : suffix) * arr[n - i - 1];
            maxProduct = Math.max(maxProduct, Math.max(prefix, suffix));
        }

        System.out.print(maxProduct);
    }
}

Python

arr = [2,3,-2,4]
maxProduct = float('-inf')
prefix = suffix = 1
n = len(arr)

for i in range(n):
    prefix = (prefix if prefix != 0 else 1) * arr[i]
    suffix = (suffix if suffix != 0 else 1) * arr[n - i - 1]
    maxProduct = max(maxProduct, prefix, suffix)

print(maxProduct)

JavaScript

let arr = [2,3,-2,4];
let maxProduct = -Infinity;
let prefix = 1, suffix = 1;

for (let i = 0; i < arr.length; i++) {
    prefix = (prefix === 0 ? 1 : prefix) * arr[i];
    suffix = (suffix === 0 ? 1 : suffix) * arr[arr.length - i - 1];
    maxProduct = Math.max(maxProduct, prefix, suffix);
}

console.log(maxProduct);

Approach 3: Kadane’s Variant (Optimal)

Idea

Track both:

  • maxEndingHere
  • minEndingHere

Because a negative number can turn a minimum product into a maximum.

Algorithm

  1. Initialize
    • maxEnding = arr[0]
    • minEnding = arr[0]
    • result = arr[0]
  2. Traverse from index 1
    • If arr[i] < 0, swap max & min
    • Update maxEnding
    • Update minEnding
    • Update result

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C

#include 

int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }

int main() {
    int arr[] = {2,3,-2,4};
    int n = 4;

    int maxEnding = arr[0];
    int minEnding = arr[0];
    int result = arr[0];

    for(int i = 1; i < n; i++) {
        if(arr[i] < 0) {
            int temp = maxEnding;
            maxEnding = minEnding;
            minEnding = temp;
        }

        maxEnding = max(arr[i], maxEnding * arr[i]);
        minEnding = min(arr[i], minEnding * arr[i]);

        result = max(result, maxEnding);
    }

    printf("%d", result);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {2,3,-2,4};
    int n = 4;

    int maxEnding = arr[0];
    int minEnding = arr[0];
    int result = arr[0];

    for(int i = 1; i < n; i++) {
        if(arr[i] < 0)
            swap(maxEnding, minEnding);

        maxEnding = max(arr[i], maxEnding * arr[i]);
        minEnding = min(arr[i], minEnding * arr[i]);

        result = max(result, maxEnding);
    }

    cout << result;
    return 0;
}

Java

public class MaxProductSubarray {
    public static void main(String[] args) {
        int[] arr = {2,3,-2,4};

        int maxEnding = arr[0];
        int minEnding = arr[0];
        int result = arr[0];

        for(int i = 1; i < arr.length; i++) {
            if(arr[i] < 0) {
                int temp = maxEnding;
                maxEnding = minEnding;
                minEnding = temp;
            }

            maxEnding = Math.max(arr[i], maxEnding * arr[i]);
            minEnding = Math.min(arr[i], minEnding * arr[i]);

            result = Math.max(result, maxEnding);
        }

        System.out.print(result);
    }
}

Python

arr = [2,3,-2,4]

maxEnding = minEnding = result = arr[0]

for i in range(1, len(arr)):
    if arr[i] < 0:
        maxEnding, minEnding = minEnding, maxEnding

    maxEnding = max(arr[i], maxEnding * arr[i])
    minEnding = min(arr[i], minEnding * arr[i])

    result = max(result, maxEnding)

print(result)

JavaScript

let arr = [2,3,-2,4];

let maxEnding = arr[0];
let minEnding = arr[0];
let result = arr[0];

for (let i = 1; i < arr.length; i++) {
    if (arr[i] < 0)
        [maxEnding, minEnding] = [minEnding, maxEnding];

    maxEnding = Math.max(arr[i], maxEnding * arr[i]);
    minEnding = Math.min(arr[i], minEnding * arr[i]);

    result = Math.max(result, maxEnding);
}

console.log(result);

Dry Run (Kadane’s Variant)

Input

[2, 3, -2, 4]
ElementmaxEndingminEndingresult
2222
3636
-2-2-126
44-486

Summary

  • Brute force is inefficient
  • Prefix–suffix handles sign changes
  • Kadane’s variant is optimal and interview-preferred
  • Handles negatives and zero efficiently

Next Problem in the Series

Find the First Missing Positive Integer


 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com