The Wayback Machine - https://web.archive.org/web/20240926234214/https://www.geeksforgeeks.org/maximum-product-subarray/
Open In App

Maximum Product Subarray

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer array, the task is to find the maximum product of any subarray.

Examples:

Input: arr[] = {-2, 6, -3, -10, 0, 2}
Output: 180
Explanation: The subarray with maximum product is {6, -3, -10} with product = 6 * (-3) * (-10) = 180

Input: arr[] = {-1, -3, -10, 0, 60}
Output: 60
Explanation: The subarray with maximum product is {60}.

[Naive Approach] By using two nested loops – O(n^2) Time and O(1) Space

The idea is to traverse over every contiguous subarray, find the product of each of these subarrays and return the maximum product among all the subarrays.

C++
// C++ program to find Maximum Product Subarray 
// using nested loops

#include <bits/stdc++.h>
using namespace std;

// Function to return the product of max product subarray
long long maxProduct(vector<int> &arr) {
    int n = arr.size();
  
    // Initializing result
    long long result = arr[0];

    for (int i = 0; i < n; i++) {
        long long mul = 1;
      
        // traversing in current subarray
        for (int j = i; j < n; j++) {
              mul *= arr[j];
          
            // updating result every time
            // to keep track of the maximum product
            result = max(result, mul);
        }
    }
    return result;
}

int main() {
    vector<int> arr = { -2, 6, -3, -10, 0, 2 };
    cout << maxProduct(arr);
    return 0;
}
C
// C program to find Maximum Product Subarray 
// using nested loops

#include <stdio.h>

// Function to return the product of max product subarray
long long maxProduct(int arr[], int n) {
    
    // Initializing result
    long long result = arr[0];

    for (int i = 0; i < n; i++) {
        long long mul = 1;
      
        // traversing in current subarray
        for (int j = i; j < n; j++) {
              mul *= arr[j];
          
            // updating result every time
            // to keep track of the maximum product
            result = (result > mul) ? result : mul;
        }
    }
    return result;
}

int main() {
    int arr[] = { -2, 6, -3, -10, 0, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%lld\n", maxProduct(arr, n));
    return 0;
}
Java
// Java program to find Maximum Product Subarray using 
// nested loops

import java.io.*;

class GfG {
  
    // Function to return the product of max product subarray
    static long maxProduct(int arr[]) { 
          int n = arr.length;
      
        // Initializing result
        long result = arr[0];

        for (int i = 0; i < n; i++) {
            long mul = 1;
          
            // traversing in current subarray
            for (int j = i; j < n; j++) {
                mul *= arr[j];
              
                // updating result every time
                // to keep track of the maximum product
                result = Math.max(result, mul);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int arr[] = { -2, 6, -3, -10, 0, 2 };
        System.out.println(maxProduct(arr));
    }
}
Python
# Python program to find Maximum Product Subarray 
# using nested loops

# Function to returns the product of max product subarray
def maxProduct(arr):
    n = len(arr)
  
    # Initializing result
    result = arr[0]

    for i in range(n):
        mul = 1
      
        # traversing in current subarray
        for j in range(i, n):
            mul *= arr[j]
          
            # updating result every time
            # to keep track of the maximum product
            result = max(result, mul)
    
    return result

if __name__ == "__main__":
    arr = [-2, 6, -3, -10, 0, 2]
    print(maxProduct(arr))
C#
// C# program to find Maximum Product Subarray 
// using nested loops

using System;

class GfG {

    // Function to return the product of max product subarray
    static long maxProduct(int[] arr) {
        int n = arr.Length;

        // Initializing result
        long result = arr[0];
        for (int i = 0; i < n; i++) {
            long mul = 1;

            // traversing in current subarray
            for (int j = i; j < n; j++) {
                mul *= arr[j];

                // updating result every time
                // to keep track of the maximum product
                result = Math.Max(result, mul);
            }
        }
        return result;
    }

    public static void Main(String[] args) {
        int[] arr = { -2, 6, -3, -10, 0, 2 };
        Console.Write(maxProduct(arr));
    }
}
JavaScript
// Javascript program to find Maximum Product Subarray 
// using nested loops

// Function to return the product of max product subarray
function maxProduct(arr) {
    const n = arr.length;
  
    // Initializing result
    let result = arr[0];

    for (let i = 0; i < n; i++) {
        let mul = BigInt(1);
      
        // Traversing in current subarray
        for (let j = i; j < n; j++) {
            mul *= arr[j]; 
          
            // Update result to keep track of the maximum product
            if(mul > result)
                result = mul;
        }
    }
    return result;
}

const arr = [-2n, 6n, -3n, -10n, 0n, 2n];
console.log(maxProduct(arr).toString());

Output
180

Time Complexity: O(n^2), where n is the size of array.
Auxiliary Space: O(1)

[Expected Approach 1] Using minimum and maximum product ending at any index – O(n) Time and O(1) Space

Let’s assume that the input array has only positive elements. Then, we can simply iterate from left to right keeping track of the maximum running product ending at any index. The maximum product would be the product ending at the last index. The problem arises when we encounter zero or a negative element.

  • If we encounter zero, then all the subarrays containing this zero will have product = 0, so zero simply resets the product of the subarray.
  • If we encounter a negative number, we need to keep track of the minimum product as well as the maximum product ending at the previous index. This is because when we multiply the minimum product with a negative number, it can give us the maximum product. So, keeping track of minimum product ending at any index is important as it can lead to the maximum product on encountering a negative number.

Step-by-step algorithm:

  • Create 3 variables, currMin, currMax and maxProd initialized to the first element of the array.
  • Iterate the indices 0 to N-1 and update the variables:
    • currMax = maximum(arr[i], currMax * arr[i], currMin * arr[i])
    • currMin= minimum(arr[i], currMax * arr[i], currMin * arr[i])
    • update the maxProd with the maximum value for each index.
  • Return maxProd as the result.
C++
// C++ program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index

#include <bits/stdc++.h>
using namespace std;

// function to find the product of max product subarray
long long maxProduct(vector<int> &arr) {
      int n = arr.size();
  
    // max product ending at the current index
    long long currMax = arr[0];

    // min product ending at the current index
    long long currMin = arr[0];

    // Initialize overall max product
    long long maxProd = arr[0];
  
    // Iterate through the array 
    for (int i = 1; i < n; i++) {
          
          // Temporary variable to store the maximum product ending 
          // at the current index
        long long temp = max({ arr[i] * 1LL, arr[i] * currMax,
                         arr[i] * currMin });
        
          // Update the minimum product ending at the current index
          currMin = min({ arr[i] * 1LL, arr[i] * currMax,
                    arr[i] * currMin });
      
          // Update the maximum product ending at the current index
        currMax = temp;
      
          // Update the overall maximum product
        maxProd = max(maxProd, currMax);
    }
    return maxProd;
}

int main() {
    vector<int> arr = { -2, 6, -3, -10, 0, 2 };
    cout << maxProduct(arr);
    return 0;
}
C
// C program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index

#include <stdio.h>
#include <limits.h>

long long max(long long a, long long b, long long c) {
    if (a >= b && a >= c) return a;
    if (b >= a && b >= c) return b;
    return c;
}

long long min(long long a, long long b, long long c) {
    if (a <= b && a <= c) return a;
    if (b <= a && b <= c) return b;
    return c;
}

// Function to find the product of max product subarray
long long maxProduct(int arr[], int n) {
    
    // max product ending at the current index
    long long currMax = arr[0];

    // min product ending at the current index
    long long currMin = arr[0];

    // Initialize overall max product
    long long maxProd = arr[0];

    // Iterate through the array
    for (int i = 1; i < n; i++) {
        
        // Temporary variable to store the maximum product ending at the
        // current index
        long long temp = max(arr[i] * 1LL, arr[i] * currMax, arr[i] * currMin);
        
        // Update the minimum product ending at the current index
        currMin = min(arr[i] * 1LL, arr[i] * currMax, arr[i] * currMin);
      
        // Update the maximum product ending at the current index
        currMax = temp;
      
        // Update the overall maximum product
        maxProd = max(maxProd, currMax, maxProd);
    }
    return maxProd;
}

int main() {
    int arr[] = { -2, 6, -3, -10, 0, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%lld\n", maxProduct(arr, n));
    return 0;
}
Java
// Java program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index

class GfG {
    static long max(long a, long b, long c) {
        return Math.max(a, Math.max(b, c));
    }

    static long min(long a, long b, long c) {
        return Math.min(a, Math.min(b, c));
    }

    // Function to find the product of max product subarray
    static long maxProduct(int[] arr) {
        int n = arr.length;

        // max product ending at the current index
        long currMax = arr[0];

        // min product ending at the current index
        long currMin = arr[0];

        // Initialize overall max product
        long maxProd = arr[0];

        // Iterate through the array
        for (int i = 1; i < n; i++) {
            
            // Temporary variable to store the maximum product ending 
            // at the current index
            long temp = max(arr[i] * 1L, arr[i] * currMax, arr[i] * currMin);

            // Update the minimum product ending at the current index
            currMin = min(arr[i] * 1L, arr[i] * currMax, arr[i] * currMin);

            // Update the maximum product ending at the current index
            currMax = temp;
            
            // Update the overall maximum product
            maxProd = Math.max(maxProd, currMax);
        }

        return maxProd;
    }

    public static void main(String[] args) {
        int[] arr = { -2, 6, -3, -10, 0, 2 };
        System.out.println(maxProduct(arr));
    }
}
Python
# Python program to find Maximum Product Subarray using Minimum
# Maximum Product ending at every index

# function to find the product of max product subarray.
def max_product(arr):
    n = len(arr)

    # max product ending at the current index
    currMax = arr[0]

    # min product ending at the current index
    currMin = arr[0]

    # Initialize overall max product
    maxProd = arr[0]

    # Iterate through the array
    for i in range(1, n):

        # Temporary variable to store the maximum product ending
        # at the current index
        temp = max(arr[i], arr[i] * currMax, arr[i] * currMin)

        # Update the minimum product ending at the current index
        currMin = min(arr[i], arr[i] * currMax, arr[i] * currMin)

        # Update the maximum product ending at the current index
        currMax = temp

        # Update the overall maximum product
        maxProd = max(maxProd, currMax)

    return maxProd


if __name__ == "__main__":
    arr = [-2, 6, -3, -10, 0, 2]
    print(max_product(arr))
C#
// C# program to find Maximum Product Subarray using Minimum
// and Maximum Product ending at every index

using System;

class GfG {
    
    // Function to find the product of max product subarray
    static long MaxProduct(int[] arr) {
        int n = arr.Length;

        // max product ending at the current index
        long currMax = arr[0];

        // min product ending at the current index
        long currMin = arr[0];

        // Initialize overall max product
        long maxProd = arr[0];

        // Iterate through the array 
        for (int i = 1; i < n; i++) {
            
            // Temporary variable to store the maximum product ending 
            // at the current index
            long temp = Math.Max(arr[i] * 1L, Math.Max(arr[i] * currMax,
                            arr[i] * currMin));

            // Update the minimum product ending at the current index
            currMin = Math.Min(arr[i] * 1L, Math.Min(arr[i] * currMax,
                            arr[i] * currMin));

            // Update the maximum product ending at the current index
            currMax = temp;

            // Update the overall maximum product
            maxProd = Math.Max(maxProd, currMax);
        }
        return maxProd;
    }

    static void Main() {
        int[] arr = { -2, 6, -3, -10, 0, 2 };
        Console.WriteLine(MaxProduct(arr));
    }
}
JavaScript
// JavaScript program to find Maximum Product Subarray using
// Minimum and Maximum Product ending at every index

function max(a, b, c) {
    return a > b ? (a > c ? a : c) : (b > c ? b : c);
}

function min(a, b, c) {
    return a < b ? (a < c ? a : c) : (b < c ? b : c);
}

// Function to find the product of max product subarray
function maxProduct(arr) {

    // Initialize the maximum and minimum products ending at
    // the current index
    let currMax = arr[0];
    let currMin = arr[0];

    // Initialize the overall maximum product
    let maxProd = arr[0];

    // Iterate through the array starting from the second element
    for (let i = 1; i < arr.length; i++) {

        // Calculate potential maximum product at this index
        const temp = max(arr[i] * currMax, arr[i] * currMin, arr[i]);

        // Update the minimum product ending at the current index
        currMin = min(arr[i] * currMax, arr[i] * currMin, arr[i]);

        // Update the maximum product ending at the current index
        currMax = temp;

        // Update the overall maximum product
        maxProd = max(maxProd, maxProd, currMax);
    }
    return maxProd;
}

const arr = [ -2n, 6n, -3n, -10n, 0n, 2n ];
console.log(maxProduct(arr).toString());

Output
180

Working:


Complexity Analysis:

  • Time Complexity: O(n), where n is the size of input array.
  • Auxiliary Space: O(1)

[Expected Approach 2] By traversing in both directions – O(n) Time and O(1) Space

We will follow a simple approach that is to traverse from the start and keep track of the running product and if the running product is greater than the max product, then we update the max product. Also, if we encounter ‘0’ then make product of all elements till now equal to 1 because from the next element, we will start a new subarray.

But what is the problem with this approach?

Problem will occur when our array will contain odd no. of negative elements. In that case, we have to reject one negative element so that we can even no. of negative elements and their product can be positive. Now, since subarray should be contiguous so we can’t simply reject any one negative element. We have to either reject the first negative element or the last negative element.

Now, if we traverse from start then only the last negative element can be rejected and if we traverse from the last then the first negative element can be rejected. So we will traverse from both ends and find the maximum product subarray.

C++
// C++ program to find Maximum Product Subarray using 
// Traversal From Starting and End of an Array

#include <bits/stdc++.h>
using namespace std;

// function to find the product of max product subarray.
long long maxProduct(vector<int> &arr) {
      int n = arr.size();
    long long maxProd = INT_MIN;
  
    // leftToRight to store product from left to Right
    long long leftToRight = 1;
  
    // rightToLeft to store product from right to left
    long long rightToLeft = 1;
  
    for (int i = 0; i < n; i++) {
        if (leftToRight == 0)
            leftToRight = 1;
        if (rightToLeft == 0)
            rightToLeft = 1;
      
        // calculate product from index left to right
        leftToRight *= arr[i];
      
        // calculate product from index right to left
        int j = n - i - 1;
        rightToLeft *= arr[j];
        maxProd = max({leftToRight, rightToLeft, maxProd});
    }
    return maxProd;
}

int main() {
    vector<int> arr = { -2, 6, -3, -10, 0, 2 };
    cout << maxProduct(arr);
    return 0;
}
C
// C program to find Maximum Product Subarray using 
// Traversal From Starting and End of an Array

#include <stdio.h>
#include <limits.h>

// function to find the product of max product subarray
long long maxProduct(int arr[], int n) {
    long long maxProd = LLONG_MIN;
  
    // leftToRight to store product from left to Right
    long long leftToRight = 1;
  
    // rightToLeft to store product from right to left
    long long rightToLeft = 1;
  
    for (int i = 0; i < n; i++) {
        if (leftToRight == 0)
            leftToRight = 1;
        if (rightToLeft == 0)
            rightToLeft = 1;
      
        // calculate product from index left to right
        leftToRight *= arr[i];
      
        // calculate product from index right to left
        int j = n - i - 1;
        rightToLeft *= arr[j];
        maxProd = (leftToRight > maxProd ? leftToRight : maxProd);
        maxProd = (rightToLeft > maxProd ? rightToLeft : maxProd);
    }
    return maxProd;
}

int main() {
    int arr[] = { -2, 6, -3, -10, 0, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%lld\n", maxProduct(arr, n));
    return 0;
}
Java
// Java program to find Maximum Product Subarray using 
// Traversal From Starting and End of an Array

class GfG {

    // function to find the product of max product subarray
    static long maxProduct(int[] arr) {
        int n = arr.length;
        long maxProd = Long.MIN_VALUE;
  
        // leftToRight to store product from left to Right
        long leftToRight = 1;
  
        // rightToLeft to store product from right to left
        long rightToLeft = 1;
  
        for (int i = 0; i < n; i++) {
            if (leftToRight == 0)
                leftToRight = 1;
            if (rightToLeft == 0)
                rightToLeft = 1;
      
            // calculate product from index left to right
            leftToRight *= arr[i];
      
            // calculate product from index right to left
            int j = n - i - 1;
            rightToLeft *= arr[j];
            maxProd = Math.max(leftToRight, 
                               Math.max(rightToLeft, maxProd));
        }
        return maxProd;
    }

    public static void main(String[] args) {
        int[] arr = { -2, 6, -3, -10, 0, 2 };
        System.out.println(maxProduct(arr));
    }
}
Python
# Python program to find Maximum Product Subarray using 
# Traversal From Starting and End of an Array

# function to find the product of max product subarray
def maxProduct(arr):
    n = len(arr)
    maxProd = float('-inf')
  
    # leftToRight to store product from left to Right
    leftToRight = 1
  
    # rightToLeft to store product from right to left
    rightToLeft = 1
  
    for i in range(n):
        if leftToRight == 0:
            leftToRight = 1
        if rightToLeft == 0:
            rightToLeft = 1
      
        # calculate product from index left to right
        leftToRight *= arr[i]
      
        # calculate product from index right to left
        j = n - i - 1
        rightToLeft *= arr[j]
        maxProd = max(leftToRight, rightToLeft, maxProd)
    
    return maxProd

arr = [-2, 6, -3, -10, 0, 2]
print(maxProduct(arr))
C#
// C# program to find Maximum Product Subarray using 
// Traversal From Starting and End of an Array

using System;

class GfG {
      
    // function to find the product of max product subarray
    static long MaxProduct(int[] arr) {
        int n = arr.Length;
        long maxProd = long.MinValue;

        // leftToRight to store product from left to Right
        long leftToRight = 1;

        // rightToLeft to store product from right to left
        long rightToLeft = 1;

        for (int i = 0; i < n; i++) {
            if (leftToRight == 0)
                leftToRight = 1;
            if (rightToLeft == 0)
                rightToLeft = 1;

            // calculate product from index left to right
            leftToRight *= arr[i];

            // calculate product from index right to left
            int j = n - i - 1;
            rightToLeft *= arr[j];
            maxProd = Math.Max(leftToRight, Math.Max(rightToLeft, maxProd));
        }
        return maxProd;
    }

    static void Main() {
        int[] arr = { -2, 6, -3, -10, 0, 2 };
        Console.WriteLine(MaxProduct(arr));
    }
}
JavaScript
// JavaScript program to find Maximum Product Subarray using 
// Traversal From Starting and End of an Array

function max(a, b, c) {
    return a > b ? (a > c ? a : c) : (b > c ? b : c);
}

function maxProduct(arr) {
    const n = arr.length;
    let ans = BigInt('-9223372036854775808');
  
    // leftToRight to store product from left to Right
    let leftToRight = BigInt(1);
  
    // rightToLeft to store product from right to left
    let rightToLeft = BigInt(1);
  
    for (let i = 0; i < n; i++) {
        if (leftToRight === BigInt(0))
            leftToRight = BigInt(1);
        if (rightToLeft === BigInt(0))
            rightToLeft = BigInt(1);
      
        // calculate product from index left to right
        leftToRight *= BigInt(arr[i]);
      
        // calculate product from index right to left
        const j = n - i - 1;
        rightToLeft *= BigInt(arr[j]);
        ans = max(leftToRight, rightToLeft, ans);
    }
    return ans.toString();
}

const arr = [-2n, 6n, -3n, -10n, 0n, 2n];
console.log(maxProduct(arr));

Output
180

Working:


Complexity Analysis:

  • Time Complexity: O(n), where n is the size of input array.
  • Auxiliary Space: O(1)


Similar Reads

Smallest pair of indices with product of subarray co-prime with product of the subarray on the left or right
Given an array arr[] of length N, the task is to find the smallest pair of indices (i, j) such that the product of elements in the subarray arr[i + 1, j - 1] is co-prime with either the product of the subarray arr[0, i] or that of the subarray arr[j, N]. If no such pair exists, the print "-1". Examples: Input: arr[] = {2, 4, 1, 3, 7}Output: (0, 2)E
12 min read
Maximum Product Subarray | Added negative product case
Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. The maximum product can be positive, negative or zero. Examples: Input : arr[] = {-2, -3, 0, -2, -40} Output : 80 Subarray : arr[3..4] i.e.{-2, -40} Input : arr[]
13 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Maximum length subarray with LCM equal to product
Given an arr[], the task is to find the maximum length of the sub-array such that the LCM of the sub-array is equal to the product of numbers in the sub-array. If no valid sub-array exists, then print -1. Note: The length of the sub-array must be ? 2. Examples: Input: arr[] = { 6, 10, 21} Output: 2 The sub-array { 10, 21 } satisfies the condition.
15+ min read
Maximize product of subarray sum with its maximum element
Given an array arr[] consisting of N positive integers, the task is to find the maximum product of the subarray sum with the maximum element of that subarray. Examples: Input: arr[] = {2, -3, 8, -2, 5}Output: 88Explanation:The required maximum product can be obtained using subarray {8, -2, 5}Therefore, maximum product = (8 + (-2) + 5) * (8) = 88. I
8 min read
Length of maximum product subarray
Given an integer array arr[] of size N, the task is to find the maximum length subarray whose products of element is non zero. . Examples: Input: arr[] = [1, 1, 0, 2, 1, 0, 1, 6, 1] Output: 3 Explanation Possible subarray whose product are non zero are [1, 1], [2, 1] and [1, 6, 1] So maximum possible length is 3.Input: arr[] = [0, 1, 2, 1, 3, 0, 0,
8 min read
Maximum subarray product modulo M
Given an array, arr[] of size N and a positive integer M, the task is to find the maximum subarray product modulo M and the minimum length of the maximum product subarray. Examples: Input: arr[] = {2, 3, 4, 2}, N = 4, M = 5Output: Maximum subarray product is 4 Minimum length of the maximum product subarray is 1 Explanation: Subarrays of length 1 ar
8 min read
Find maximum product of Bitwise AND and Bitwise OR of K-size subarray
Given an array arr[] containing N integers and an integer K, the task is to find the maximum value of the product of Bitwise AND and Bitwise OR of all elements of a K-sized subarray. Example: Input: arr[] = {1, 2, 3, 4}, K = 2Output: 6Explanation: Bitwise AND and Bitwise XOR of all K-sized subarrays is {(0, 3), (2, 3), (0, 7)} respectively. Therefo
9 min read
Maximum Product Subarray | Set 3
Given an array A[] that contains both positive and negative integers, find the maximum product subarray. Examples : Input: A[] = { 6, -3, -10, 0, 2 } Output: 180 // The subarray is {6, -3, -10} Input: A[] = {-1, -3, -10, 0, 60 } Output: 60 // The subarray is {60} Input: A[] = { -2, -3, 0, -2, -40 } Output: 80 // The subarray is {-2, -40}Recommended
7 min read
Maximum Product Subarray | Set 2 (Using Two Traversals)
Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. Examples : Input: arr[] = {6, -3, -10, 0, 2} Output: 180 // The subarray is {6, -3, -10} Input: arr[] = {-1, -3, -10, 0, 60} Output: 60 // The subarray is {60} In
9 min read
Javascript Program for Maximum Product Subarray
Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. Examples: Input: arr[] = {6, -3, -10, 0, 2} Output: 180 // The subarray is {6, -3, -10} Input: arr[] = {-1, -3, -10, 0, 60} Output: 60 // The subarray is {60} Inp
4 min read
Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k
Given an array arr[] and an integer k, the task is to find the maximum product from the array such that the frequency sum of all repeating elements in the product is ≤ 2 * k, where frequency sum is the sum of frequencies of all the elements in the product that appear more than once. For example, if we choose a product 1 * 1 * 2 * 3 * 4 * 5 * 6 * 6
7 min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having maximum sum. Examples: Input: arr[] = {1, 4, 2, 10
11 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Maximize the subarray sum after multiplying all elements of any subarray with X
Given an array arr[] of N integers and an integer X. We can choose any sub-array and multiply all its element by X. After multiplication, find the sub-array with the maximum sum. The task is to multiply the sub-array in such a way that the final sub-array sum is maximized. Examples: Input: arr[] = { -3, 8, -2, 1, -6 }, X = -1 Output: 15 Choose the
15+ min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Maximum element in an array such that its previous and next element product is maximum
Given an array arr[] of N integers, the task is to print the largest element among the array such that its previous and next element product is maximum.Examples: Input: arr[] = {5, 6, 4, 3, 2} Output: 6 The product of the next and the previous elements for every element of the given array are: 5 -> 2 * 6 = 12 6 -> 5 * 4 = 20 4 -> 6 * 3 = 1
6 min read
Split array into maximum possible subsets having product of their length with the maximum element at least K
Given an array arr[] consisting of N integers and a positive integer K, the task is to maximize the number of subsets having a product of its size and its maximum element at least K by dividing array element into disjoint subsets. Examples: Input: N = 5, K = 4, arr[] = {1, 5, 4, 2, 3}Output: 3Explanation:The array can be split into 3 possible subse
6 min read
Smallest subarray with product divisible by k
Given an array of non-negative numbers, find length of smallest subarray whose product is a multiple of k. Examples : Input : arr[] = {1, 9, 16, 5, 4, 3, 2} k = 720 Output: 3 The smallest subarray is {9, 16, 5} whose product is 720. Input : arr[] = {1, 2, 4, 5, 6} K = 96 Output : No such subarray exists The idea is simple. We traverse through all s
7 min read
Length of longest subarray with product greater than or equal to 0
Given an array arr[] of N integers, the task is to find the length of the longest subarray whose product is greater than or equals to 0.Examples: Input: arr[] = {-1, 1, 1, -2, 3, 2, -1 } Output: 6 Explanation: The longest subarray with product ? 0 = {1, 1, -2, 3, 2, -1} and {-1, 1, 1, -2, 3, 2}. Length of each = 6. Input: arr[] = {-1, -2, -3, -4} O
6 min read
Length of longest subarray with negative product
Given an array arr[] of N elements. The task is to find the length of the longest subarray such that the product of the subarray is negative. If there is no such subarray available, print -1.Examples: Input: N = 6, arr[] = {-1, 2, 3, 2, 1, -4} Output: 5 Explanation: In the example the subarray in range [1, 5] has product -12 which is negative, so t
6 min read
Smallest subarray whose product leaves remainder K when divided by size of the array
Given an array arr[] of N integers and an integer K, the task is to find the length of the smallest subarray whose product when divided by N gives remainder K. If no such subarray exists the print "-1". Examples: Input: N = 3, arr = {2, 2, 6}, K = 1 Output: 2 Explanation: All possible subarrays are: {2} -> 2(mod 3) = 2 {2} -> 2(mod 3) = 2 {6}
6 min read
Longest subarray with odd product
Given an array arr[] consisting of N elements, the task is to find the length of longest subarray with odd product.Examples: Input: arr[] = {3, 5, 2, 1} Output: 2 Explanation: Subarrays with consecutive odd elements are {3, 5}, and {1}. Since, {3, 5} is the longer, the answer is 2.Input: arr[] = {8, 5, 3, 1, 0} Output: 3 Explanation: Longest subarr
4 min read
Maximize product of subarray sum with its minimum element
Given an array arr[] consisting of N positive integers, the task is to find the maximum product of subarray sum with the minimum element of that subarray. Examples: Input: arr[] = {3, 1, 6, 4, 5, 2}Output: 60Explanation:The required maximum product can be obtained using subarray {6, 4, 5}Therefore, maximum product = (6 + 4 + 5) * (4) = 60 Input: ar
10 min read
Maximize product of a strictly increasing or decreasing subarray
Given an array arr[] of size N, the task is to find the maximum product from any subarray consisting of elements in strictly increasing or decreasing order. Examples: Input: arr[] = { 1, 2, 10, 8, 1, 100, 101 } Output: 10100 Explanation: Increasing subarray with maximum product is {1, 100, 101}. Therefore, the required output is 1 * 100 * 101. Inpu
14 min read