Find all possible subarrays having product less than or equal to K

Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K.

Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 
Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] 
Explanation: 
All possible subarrays having product ≤ K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5}, {6}, {2}.

Input: arr[] = {2, 7, 1, 4}, K = 7 
Output: [[2], [7], [1], [7, 1], [4], [1, 4]]

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays from the given array and for each subarray, check if its product is less than or equal to K or not and print accordingly. 

Time Complexity: O(N3
Auxiliary Space: O(N) 
 



Efficient Approach: The above approach can be optimized by observing that: 

If the product of all the elements of a subarray is less than or equal to K, then all the subarrays possible from this subarray also has product less than or equal to K. Therefore, these subarrays need to be included in the answer as well.

Follow the steps below to solve the problem:  

  1. Initialize a pointer start pointing to the first index of the array.
  2. Iterate over the array and keep calculating the product of the array elements and store it in a variable, say multi.
  3. If multi exceeds K: keep dividing multi by arr[start] and keep incrementing start until multi reduces to ≤ K.
  4. If multi ≤ K: Iterate from the current index to start, and store the subarrays in an Arraylist.
  5. Finally, once all subarrays are generated, print the Arraylist which contains all the subarrays obtained.

Below is the implementation of the above approach: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to return all possible
// subarrays having product less
// than or equal to K
vector<vector<int>> maxSubArray(int arr[], int n,
                                int K)
{
     
    // Store the required subarrays
    vector<vector<int>> solution;
     
    // Stores the product of
    // current subarray
    int multi = 1;
     
    // Stores the starting index
    // of the current subarray
    int start = 0;
     
    // Check for empty array
    if (n <= 1 || K < 0)
    {
        return solution;
    }
     
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
         
        // Calculate product
        multi = multi * arr[i];
     
        // If product exceeds K
        while (multi > K)
        {
             
            // Reduce product
            multi = multi / arr[start];
     
            // Increase starting index
            // of current subarray
            start++;
        }
     
        // Stores the subarray elements
        vector<int> list;
     
        // Store the subarray elements
        for(int j = i; j >= start; j--)
        {
            list.insert(list.begin(), arr[j]);
     
            // Add the subarrays
            // to the list
            solution.push_back(list);
        }
    }
     
    // Return the final
    // list of subarrays
    return solution;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 7, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 7;
     
    vector<vector<int>> v = maxSubArray(arr, n, K);
    cout << "[";
     
    bool first = true;
    for(auto x : v)
    {
        if (!first)
        {
            cout << ", ";
        }
        else
        {
            first = false;
        }
        cout << "[";
         
        bool ff = true;
        for(int y : x)
        {
            if (!ff)
            {
                cout << ", ";
            }
            else
            {
                ff = false;
            }
            cout << y;
        }
        cout << "]";
    }
    cout << "]";
     
    return 0;
}
 
// This code is contributed by rutvik_56

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to return all possible
    // subarrays having product less
    // than or equal to K
    public static List<List<Integer> > maxSubArray(
        int[] arr, int K)
    {
 
        // Store the required subarrays
        List<List<Integer> > solution
            = new ArrayList<>();
 
        // Stores the product of
        // current subarray
        int multi = 1;
 
        // Stores the starting index
        // of the current subarray
        int start = 0;
 
        // Check for empty array
        if (arr.length <= 1 || K < 0) {
            return new ArrayList<>();
        }
 
        // Iterate over the array
        for (int i = 0; i < arr.length; i++) {
 
            // Calculate product
            multi = multi * arr[i];
 
            // If product exceeds K
            while (multi > K) {
 
                // Reduce product
                multi = multi / arr[start];
 
                // Increase starting index
                // of current subarray
                start++;
            }
 
            // Stores the subarray elements
            List<Integer> list
                = new ArrayList<>();
 
            // Store the subarray elements
            for (int j = i; j >= start; j--) {
 
                list.add(0, arr[j]);
 
                // Add the subarrays
                // to the list
                solution.add(
                    new ArrayList<>(list));
            }
        }
 
        // Return the final
        // list of subarrays
        return solution;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 2, 7, 1, 4 };
        int K = 7;
 
        System.out.println(maxSubArray(arr, K));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return all possible
// subarrays having product less
// than or equal to K
public static List<List<int>> maxSubArray(int[] arr,
                                          int K)
{
  // Store the required subarrays
  List<List<int> > solution = new List<List<int>>();
 
  // Stores the product of
  // current subarray
  int multi = 1;
 
  // Stores the starting index
  // of the current subarray
  int start = 0;
 
  // Check for empty array
  if (arr.Length <= 1 || K < 0)
  {
    return new List<List<int>>();
  }
 
  // Iterate over the array
  for (int i = 0; i < arr.Length; i++)
  {
    // Calculate product
    multi = multi * arr[i];
 
    // If product exceeds K
    while (multi > K)
    {
      // Reduce product
      multi = multi / arr[start];
 
      // Increase starting index
      // of current subarray
      start++;
    }
 
    // Stores the subarray elements
    List<int> list = new List<int>();
 
    // Store the subarray elements
    for (int j = i; j >= start; j--)
    {
      list.Insert(0, arr[j]);
 
      // Add the subarrays
      // to the list
      solution.Add(new List<int>(list));
    }
  }
 
  // Return the final
  // list of subarrays
  return solution;
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] arr = {2, 7, 1, 4};
  int K = 7;
  List<List<int> > list = maxSubArray(arr, K);
  foreach(List<int> i in list)
  {
    Console.Write("[");
    foreach(int j in i)
    {
      Console.Write(j);
      if(i.Count > 1)
        Console.Write(",");
    }
    Console.Write("]");
  }
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

[[2], [7], [1], [7, 1], [4], [1, 4]]




 

Time Complexity: O(N2)
Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar, rutvik_56