JavaScript Program for Maximum Product Subarray

A subarray is a contiguous portion of an array. In the maximum product subarray problem, we need to find the subarray whose elements have the largest product when multiplied together. This is a classic dynamic programming problem with interesting edge cases involving negative numbers and zeros.

Problem Analysis

The challenge becomes complex when dealing with different types of numbers:

  • All positive numbers: The entire array gives maximum product
  • Contains zeros: Array splits into segments at zero positions
  • Contains negative numbers: Even count of negatives gives positive product, odd count gives negative

Example Cases

Case 1: All positive numbers

Given array: [1, 2, 3, 4, 2, 2, 1]
Maximum product: 96 (entire array)

Case 2: Contains zeros

Given array: [1, 2, 3, 0, 4, 5, 1, 0, 9, 2, 0, 0]
Maximum product: 20 (subarray [4, 5, 1])

Case 3: Contains negative numbers

Given array: [-40, -2, 0, 1, 5, -9, -8, -6, 0, 9, 8, 3]
Maximum product: 360 (subarray [1, 5, -9, -8])

Method 1: Brute Force Approach

This approach generates all possible subarrays and calculates their products to find the maximum.

// Function to find maximum product subarray using brute force
function maxProductBruteForce(arr) {
    var len = arr.length;
    var maxProduct = arr[0]; // Initialize with first element
    
    // Check all possible subarrays
    for (var i = 0; i < len; i++) {
        var currentProduct = 1;
        for (var j = i; j < len; j++) {
            currentProduct *= arr[j];
            if (currentProduct > maxProduct) {
                maxProduct = currentProduct;
            }
        }
    }
    
    console.log("Maximum product using brute force: " + maxProduct);
    return maxProduct;
}

// Test cases
var arr1 = [1, 2, 3, 4, 2, 2, 1];
maxProductBruteForce(arr1);

var arr2 = [1, 2, 3, 0, 4, 5, 1, 0, 9, 2, 0, 0];
maxProductBruteForce(arr2);

var arr3 = [-40, -2, 0, 1, 5, -9, -8, -6, 0, 9, 8, 3];
maxProductBruteForce(arr3);
Maximum product using brute force: 96
Maximum product using brute force: 20
Maximum product using brute force: 360

Method 2: Optimized Dynamic Programming

This efficient approach tracks both maximum and minimum products at each position, as negative numbers can flip the values.

// Function to find maximum product subarray using dynamic programming
function maxProductOptimized(arr) {
    var n = arr.length;
    if (n === 0) return 0;
    
    var maxProduct = arr[0];
    var maxEndingHere = arr[0];
    var minEndingHere = arr[0];
    
    for (var i = 1; i < n; i++) {
        // Store maxEndingHere temporarily
        var temp = maxEndingHere;
        
        // Calculate new max and min ending at current position
        maxEndingHere = Math.max(arr[i], Math.max(maxEndingHere * arr[i], minEndingHere * arr[i]));
        minEndingHere = Math.min(arr[i], Math.min(temp * arr[i], minEndingHere * arr[i]));
        
        // Update global maximum
        maxProduct = Math.max(maxProduct, maxEndingHere);
    }
    
    console.log("Maximum product using optimized approach: " + maxProduct);
    return maxProduct;
}

// Test cases
var arr1 = [1, 2, 3, 4, 2, 2, 1];
maxProductOptimized(arr1);

var arr2 = [1, 2, 3, 0, 4, 5, 1, 0, 9, 2, 0, 0];
maxProductOptimized(arr2);

var arr3 = [-40, -2, 0, 1, 5, -9, -8, -6, 0, 9, 8, 3];
maxProductOptimized(arr3);
Maximum product using optimized approach: 96
Maximum product using optimized approach: 20
Maximum product using optimized approach: 360

Complexity Analysis

Method Time Complexity Space Complexity
Brute Force O(N²) O(1)
Optimized DP O(N) O(1)

Key Points

  • Track both maximum and minimum products due to negative number behavior
  • Zeros reset the product calculation
  • The optimized solution uses Kadane's algorithm variation
  • Handle edge cases like single elements and all negative arrays

Conclusion

The maximum product subarray problem requires careful handling of negative numbers and zeros. The optimized dynamic programming approach provides O(N) time complexity while maintaining constant space usage, making it efficient for large arrays.

Updated on: 2026-03-15T23:19:01+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements