Maximice las subsecuencias que tienen elementos de array que no excedan la longitud de la subsecuencia

Dada una array arr[] que consta de N enteros positivos, la tarea es maximizar el número de subsecuencias que se pueden obtener de una array de modo que cada elemento arr[i] que sea parte de cualquier subsecuencia no exceda la longitud de esa subsecuencia .

Ejemplos: 

Entrada: arr[] = {1, 1, 1, 1} 
Salida:
Explicación: 
Forme 4 subsecuencias de 1 que satisfagan la condición dada {1}, {1}, {1}, {1}.

Entrada: arr[] = {2, 2, 3, 1, 2, 1} 
Salida:
Explicación: 
El grupo posible es {1}, {1}, {2, 2} 
Entonces, la salida es 3.

Enfoque: La idea es usar la Técnica Greedy para resolver este problema. Siga los pasos a continuación para resolver el problema: 

  1. Inicialice un mapa para almacenar la frecuencia de cada elemento de la array .
  2. Inicialice una variable, digamos contar hasta 0, para almacenar el número total de subsecuencias obtenidas.
  3. Mantenga un registro de la cantidad de elementos que quedan por agregar.
  4. Ahora, itere sobre el mapa y cuente la cantidad de elementos que se pueden incluir en un grupo en particular.
  5. Siga agregando los elementos en las subsecuencias válidas.
  6. Después de completar los pasos anteriores, imprima el recuento de subsecuencias.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the number
// of subsequences that can be formed
int No_Of_subsequences(map<int, int> mp)
{
    // Stores the number of subsequences
    int count = 0;
    int left = 0;
 
    // Iterate over the map
    for (auto x : mp) {
 
        x.second += left;
 
        // Count the number of subsequences
        // that can be formed from x.first
        count += (x.second / x.first);
 
        // Number of occurrences of
        // x.first which are left
        left = x.second % x.first;
    }
 
    // Return the number of subsequences
    return count;
}
 
// Function to create the maximum count
// of subsequences that can be formed
void maximumsubsequences(int arr[], int n)
{
    // Stores the frequency of arr[]
    map<int, int> mp;
 
    // Update the frequency
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Print the number of subsequences
    cout << No_Of_subsequences(mp);
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 1, 1, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maximumsubsequences(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to calculate the number
// of subsequences that can be formed
public static int No_Of_subsequences(HashMap<Integer,
                                             Integer> mp)
{
     
    // Stores the number of subsequences
    int count = 0;
    int left = 0;
 
    // Iterate over the map
    for(Map.Entry<Integer, Integer> x : mp.entrySet())
    {
        mp.replace(x.getKey(), x.getValue() + left);
         
        // Count the number of subsequences
        // that can be formed from x.first
        count += (x.getValue() / x.getKey());
 
        // Number of occurrences of
        // x.first which are left
        left = x.getValue() % x.getKey();
    }
 
    // Return the number of subsequences
    return count;
}
 
// Function to create the maximum count
// of subsequences that can be formed
public static void maximumsubsequences(int[] arr,
                                       int n)
{
     
    // Stores the frequency of arr[]
    HashMap<Integer, Integer> mp = new HashMap<>();
 
    // Update the frequency
    for(int i = 0; i < n; i++)
    {
        if (mp.containsKey(arr[i]))
        {
            mp.replace(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
    }
 
    // Print the number of subsequences
    System.out.println(No_Of_subsequences(mp));
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 1, 1, 1 };
 
    int N = arr.length;
 
    // Function call
    maximumsubsequences(arr, N);
}
}
 
// This code is contributed divyeshrabadiya07

Python3

# Python3 program for
# the above approach
from collections import defaultdict
 
# Function to calculate
# the number of subsequences
# that can be formed
def No_Of_subsequences(mp):
 
    # Stores the number
    # of subsequences
    count = 0
    left = 0
 
    # Iterate over the map
    for x in mp:
 
        mp[x] += left
 
        # Count the number of
        # subsequences that can
        # be formed from x.first
        count += (mp[x] // x)
 
        # Number of occurrences of
        # x.first which are left
        left = mp[x] % x
    
    # Return the number
    # of subsequences
    return count
 
# Function to create the
# maximum count of subsequences
# that can be formed
def maximumsubsequences(arr, n):
 
    # Stores the frequency of arr[]
    mp = defaultdict (int)
 
    # Update the frequency
    for i in range (n):
        mp[arr[i]] += 1
 
    # Print the number of subsequences
    print(No_Of_subsequences(mp))
 
# Driver Code
if __name__ == "__main__":
   
    # Given array arr[]
    arr = [1, 1, 1, 1]
 
    N = len(arr)
 
    # Function Call
    maximumsubsequences(arr, N)
 
# This code is contributed by Chitranayal

C#

// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Function to calculate the number
// of subsequences that can be formed
public static int No_Of_subsequences(Dictionary<int,
                                                int> mp)
{
  // Stores the number
  // of subsequences
  int count = 0;
  int left = 0;
 
  // Iterate over the map
  foreach(KeyValuePair<int,
                       int> x in mp)
  {
    if(!mp.ContainsKey(x.Key))
      mp.Add(x.Key, x.Value + left);
 
    // Count the number of subsequences
    // that can be formed from x.first
    count += (x.Value / x.Key);
 
    // Number of occurrences of
    // x.first which are left
    left = x.Value % x.Key;
  }
 
  // Return the number of subsequences
  return count;
}
 
// Function to create the maximum count
// of subsequences that can be formed
public static void maximumsubsequences(int[] arr,
                                       int n)
{
  // Stores the frequency of []arr
  Dictionary<int,
             int> mp = new Dictionary<int,
                                      int>();
   
  // Update the frequency
  for(int i = 0; i < n; i++)
  {
    if (mp.ContainsKey(arr[i]))
    {
      mp[arr[i]] =  mp[arr[i]] + 1;
    }
    else
    {
      mp.Add(arr[i], 1);
    }
  }
 
  // Print the number of subsequences
  Console.WriteLine(No_Of_subsequences(mp));
}
 
// Driver code
public static void Main(String[] args)
{
  // Given array []arr
  int []arr = {1, 1, 1, 1};
 
  int N = arr.Length;
 
  // Function call
  maximumsubsequences(arr, N);
}
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
// Javascript program for the above approach
 
// Function to calculate the number
// of subsequences that can be formed
function No_Of_subsequences(mp)
{
    // Stores the number of subsequences
    var count = 0;
    var left = 0;
 
    // Iterate over the map
    mp.forEach((value, key) => {
         
        value += left;
 
        // Count the number of subsequences
        // that can be formed from key
        count += (value / key);
 
        // Number of occurrences of
        // x.first which are left
        left = value % key;
    });
 
    // Return the number of subsequences
    return count;
}
 
// Function to create the maximum count
// of subsequences that can be formed
function maximumsubsequences(arr, n)
{
 
    // Stores the frequency of arr[]
    var mp = new Map();
 
    // Update the frequency
    for (var i = 0; i < n; i++)
    {
        if(mp.has(arr[i]))
            mp.set(arr[i], mp.get(arr[i])+1)
        else
            mp.set(arr[i], 1);
    }
 
    // Print the number of subsequences
    document.write( No_Of_subsequences(mp));
}
 
// Driver Code
 
// Given array arr[]
var arr = [1, 1, 1, 1];
var N = arr.length;
 
// Function Call
maximumsubsequences(arr, N);
 
// This code is contributed by itsok.
</script>
Producción: 

4

 

Complejidad de tiempo: O(N*log N) 
Espacio auxiliar: O(N) 

Publicación traducida automáticamente

Artículo escrito por satyajitmahunta98 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *