Dada una array arr que contiene N elementos, encuentre la longitud de la subsecuencia más larga tal que sea una permutación válida de una longitud particular. Si no existe tal secuencia de permutación, imprima 0.
Ejemplos:
Entrada: arr[] = {3, 2, 1, 6, 5}
Salida: 3
Explicación:
La subsecuencia de permutación más larga será [3, 2, 1].
Entrada: arr[]= {2, 3, 4, 5}
Salida: 0
Explicación:
No hay una subsecuencia de permutación válida presente porque falta el elemento 1.
Enfoque: el problema mencionado anteriormente es sobre la subsecuencia de permutación, por lo que el orden de los elementos de la array es irrelevante, solo importa la frecuencia de cada elemento . Si la array tiene una longitud N, entonces la longitud máxima posible para la secuencia de permutación es N y la longitud mínima posible es 0 . Si la subsecuencia de longitud L es una permutación válida, entonces todos los elementos de 1 a L deben estar presentes .
- Cuente la frecuencia de los elementos en el rango [1, N] de la array
- Iterar a través de todos los elementos de 1 a N en la array y contar las iteraciones hasta que se observe una frecuencia de 0. Si la frecuencia de un elemento es ‘0’, devuelve el recuento actual de iteraciones como la longitud requerida.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ Program to find length of // Longest Permutation Subsequence // in a given array #include <bits/stdc++.h> using namespace std; // Function to find the // longest permutation subsequence int longestPermutation(int a[], int n) { // Map data structure to // count the frequency of each element map<int, int> freq; for (int i = 0; i < n; i++) { freq[a[i]]++; } int len = 0; for (int i = 1; i <= n; i++) { // If frequency of element is 0, // then we can not move forward // as every element should be present if (freq[i] == 0) { break; } // Increasing the length by one len++; } return len; } // Driver Code int main() { int arr[] = { 3, 2, 1, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << longestPermutation(arr, n) << "\n"; return 0; }
Java
// Java Program to find length of // Longest Permutation Subsequence // in a given array import java.util.*; class GFG{ // Function to find the // longest permutation subsequence static int longestPermutation(int arr[], int n) { // Map data structure to // count the frequency of each element HashMap<Integer,Integer> freq = new HashMap<Integer,Integer>(); for (int i = 0; i < n; i++) { if(freq.containsKey(arr[i])){ freq.put(arr[i], freq.get(arr[i])+1); }else{ freq.put(arr[i], 1); } } int len = 0; for (int i = 1; i <= n; i++) { // If frequency of element is 0, // then we can not move forward // as every element should be present if (!freq.containsKey(i)) { break; } // Increasing the length by one len++; } return len; } // Driver Code public static void main(String[] args) { int arr[] = { 3, 2, 1, 6, 5 }; int n = arr.length; System.out.print(longestPermutation(arr, n)); } } // This code is contributed by Rajput-Ji
C#
// C# Program to find length of // longest Permutation Subsequence // in a given array using System; using System.Collections.Generic; public class GFG{ // Function to find the // longest permutation subsequence static int longestPermutation(int []arr, int n) { // Map data structure to // count the frequency of each element Dictionary<int,int> freq = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { if(freq.ContainsKey(arr[i])){ freq[arr[i]] = freq[arr[i]] + 1; }else{ freq.Add(arr[i], 1); } } int len = 0; for (int i = 1; i <= n; i++) { // If frequency of element is 0, // then we can not move forward // as every element should be present if (!freq.ContainsKey(i)) { break; } // Increasing the length by one len++; } return len; } // Driver Code public static void Main(String[] args) { int []arr = { 3, 2, 1, 6, 5 }; int n = arr.Length; Console.Write(longestPermutation(arr, n)); } } // This code is contributed by 29AjayKumar
Python3
# Program to find length of # Longest Permutation Subsequence # in a given array from collections import defaultdict # Function to find the # longest permutation subsequence def longestPermutation(a, n): # Map data structure to # count the frequency of each element freq = defaultdict(int) for i in range( n ): freq[a[i]] += 1 length = 0 for i in range(1 , n + 1): # If frequency of element is 0, # then we can not move forward # as every element should be present if (freq[i] == 0): break # Increasing the length by one length += 1 return length # Driver Code if __name__ == "__main__": arr = [ 3, 2, 1, 6, 5 ] n = len(arr) print(longestPermutation(arr, n)) # This code is contributed by chitranayal
Javascript
<script> // Javascript Program to find length of // Longest Permutation Subsequence // in a given array // Function to find the // longest permutation subsequence function longestPermutation(arr, n) { // Map data structure to // count the frequency of each element let freq = new Map(); for (let i = 0; i < n; i++) { if(freq.has(arr[i])){ freq.set(arr[i], freq.get(arr[i])+1); }else{ freq.set(arr[i], 1); } } let len = 0; for (let i = 1; i <= n; i++) { // If frequency of element is 0, // then we can not move forward // as every element should be present if (!freq.has(i)) { break; } // Increasing the length by one len++; } return len; } // Driver code let arr = [ 3, 2, 1, 6, 5 ]; let n = arr.length; document.write(longestPermutation(arr, n)); </script>
3
Complejidad temporal: O(N)
Complejidad espacial auxiliar: O(N)