📌  相关文章
📜  查找所有乘积小于或等于K的子数组

📅  最后修改于: 2021-04-25 00:32:22             🧑  作者: Mango

给定一个 array arr [] ,任务是打印所有可能的子数组,这些子数组的元素乘积小于或等于K。

天真的方法:解决问题的最简单方法是从给定数组生成所有可能的子数组,并针对每个子数组检查其乘积是否小于或等于K并进行相应打印。

时间复杂度: O(N 3 )
辅助空间: O(N)

高效的方法:可以通过观察以下方法来优化上述方法:

请按照以下步骤解决问题:

  1. 初始化一个指针,开始指向数组的第一个索引。
  2. 遍历数组,并继续计算数组元素的乘积,并将其存储在变量中,例如multi
  3. 如果多超过K:保持除以ARR[开始]和不断递增开始直到降至≤ķ。
  4. 如果multi≤K 从当前索引迭代到start ,并将子数组存储在Arraylist中。
  5. 最后,一旦生成了所有子数组,请打印包含所有获得的子数组的Arraylist

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
// Function to return all possible
// subarrays having product less
// than or equal to K
vector> maxSubArray(int arr[], int n,
                                int K)
{
     
    // Store the required subarrays
    vector> 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 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> 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


Java
// 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 > maxSubArray(
        int[] arr, int K)
    {
 
        // Store the required subarrays
        List > 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 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));
    }
}


Python3
# Python3 program to implement
# the above approach
  
# Function to return all possible
# subarrays having product less
# than or equal to K
def maxSubArray(arr, n, K):
      
    # Store the required subarrays
    solution = []
      
    # Stores the product of
    # current subarray
    multi = 1
      
    # Stores the starting index
    # of the current subarray
    start = 0
      
    # Check for empty array
    if (n <= 1 or K < 0):
        return solution
     
    # Iterate over the array
    for i in range(n):
         
        # 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 += 1
      
        # Stores the subarray elements
        li = []
         
        j = i
         
        # Store the subarray elements
        while(j >= start):       
            li.insert(0, arr[j])
      
            # Add the subarrays
            # to the li
            solution.append(list(li))
            j -= 1
      
    # Return the final
    # li of subarrays
    return solution
     
# Driver Code
if __name__=='__main__':
     
    arr = [ 2, 7, 1, 4 ]
    n = len(arr)
    K = 7
      
    v = maxSubArray(arr, n, K)
     
    print(v)
      
# This code is contributed by pratham76


C#
// 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> maxSubArray(int[] arr,
                                          int K)
{
  // Store the required subarrays
  List > solution = new List>();
 
  // 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>();
  }
 
  // 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 list = new List();
 
    // 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(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 = maxSubArray(arr, K);
  foreach(List 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


输出:
[[2], [7], [1], [7, 1], [4], [1, 4]]

时间复杂度: O(N 2 )
辅助空间: O(1)