logo

Nejdelší rostoucí dílčí sekvence (LIS)

Dané pole arr[] velikosti N , úkolem je najít délku nejdelší rostoucí podsekvence (LIS), tedy nejdelší možné podsekvence, ve které jsou prvky podsekvence seřazeny ve vzestupném pořadí.

LIS

Nejdelší rostoucí subsekvence



Příklady:

Vstup: arr[] = {3, 10, 2, 1, 20}
Výstup: 3
Vysvětlení: Nejdelší rostoucí podsekvence je 3, 10, 20

Vstup: arr[] = {50, 3, 10, 7, 40, 80}
Výstup: 4
Vysvětlení: Nejdelší rostoucí podsekvence je {3, 7, 40, 80}



abecedy k číslům

Vstup: arr[] = {30, 20, 10}
Výstup: 1
Vysvětlení: Nejdelší rostoucí dílčí sekvence jsou {30}, {20} a (10)

Vstup: arr[] = {10, 20, 35, 80}
Výstup: 4
Vysvětlení: Celé pole je seřazeno

Použití nejdelší rostoucí sekvence Rekurze :

Myšlenka procházet vstupní pole zleva doprava a najít délku nejdelší rostoucí subsekvence (LIS) končící každým prvkem arr[i]. Nechť délka nalezená pro arr[i] je L[i]. Na konci vrátíme maximum ze všech hodnot L[i]. Nyní vyvstává otázka, jak vypočítáme L[i]? K tomu použijeme rekurzi, vezmeme v úvahu všechny menší prvky vlevo od arr[i], rekurzivně vypočítáme hodnotu LIS pro všechny menší prvky vlevo, vezmeme maximum ze všech a přidáme k tomu 1. Pokud nalevo od prvku není žádný menší prvek, vrátíme 1.



Nechat L(i) být délka LIS končící na indexu i tak, že arr[i] je posledním prvkem LIS. Pak lze L(i) rekurzivně zapsat jako:

np tečka
  • L(i) = 1 + max(L(j) ), kde 0
  • L(i) = 1, pokud žádné takové j neexistuje.

Formálně délka LIS končící na indexu i , je o 1 větší než maximum délek všech LIS končících na nějakém indexu j takové, že arr[j] kde j .

Vidíme, že výše uvedený rekurentní vztah následuje optimální spodní konstrukce vlastnictví.

Ilustrace:

Madhubala

Pro lepší pochopení postupujte podle níže uvedeného obrázku:

Zvažte arr[] = {3, 10, 2, 11}

L(i): Označuje LIS podpole končící na pozici „i“

Strom rekurze

Strom rekurze

Chcete-li implementovat výše uvedený nápad, postupujte podle níže uvedených kroků:

  • Vytvořte rekurzivní funkci.
  • Pro každé rekurzivní volání iterujte z i = 1 na aktuální pozici a proveďte následující:
    • Najděte možnou délku nejdelší rostoucí podsekvence končící na aktuální pozici, pokud předchozí sekvence končila v i .
    • Podle toho aktualizujte maximální možnou délku.
  • Opakujte to pro všechny indexy a najděte odpověď

Níže je uvedena implementace rekurzivního přístupu:

java random math random
C++
// A Naive C++ recursive implementation // of LIS problem #include  using namespace std; // To make use of recursive calls, this // function must return two things: // 1) Length of LIS ending with element // arr[n-1]. // We use max_ending_here for this purpose // 2) Overall maximum as the LIS may end // with an element before arr[n-1] max_ref // is used this purpose. // The value of LIS of full array of size // n is stored in *max_ref which is // our final result int _lis(int arr[], int n, int* max_ref) {  // Base case  if (n == 1)  return 1;  // 'max_ending_here' is length of  // LIS ending with arr[n-1]  int res, max_ending_here = 1;  // Recursively get all LIS ending with  // arr[0], arr[1] ... arr[n-2]. If  // arr[i-1] is smaller than arr[n-1],  // and max ending with arr[n-1] needs  // to be updated, then update it  for (int i = 1; i < n; i++) {  res = _lis(arr, i, max_ref);  if (arr[i - 1] < arr[n - 1]  && res + 1>max_ending_here) max_ending_here = res + 1;  } // Porovnejte max_ending_here s // celkovým max. A v případě potřeby aktualizujte // celkové maximum, pokud (*max_ref< max_ending_here)  *max_ref = max_ending_here;  // Return length of LIS ending  // with arr[n-1]  return max_ending_here; } // The wrapper function for _lis() int lis(int arr[], int n) {  // The max variable holds the result  int max = 1;  // The function _lis() stores its  // result in max  _lis(arr, n, &max);  // Returns max  return max; } // Driver program to test above function int main() {  int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = sizeof(arr) / sizeof(arr[0]);  // Function call  cout << 'Length of lis is ' << lis(arr, n);  return 0; }>
C
// A Naive C recursive implementation // of LIS problem #include  #include  // To make use of recursive calls, this // function must return two things: // 1) Length of LIS ending with element arr[n-1]. // We use max_ending_here for this purpose // 2) Overall maximum as the LIS may end with // an element before arr[n-1] max_ref is // used this purpose. // The value of LIS of full array of size n // is stored in *max_ref which is our final result int _lis(int arr[], int n, int* max_ref) {  // Base case  if (n == 1)  return 1;  // 'max_ending_here' is length of LIS  // ending with arr[n-1]  int res, max_ending_here = 1;  // Recursively get all LIS ending with arr[0],  // arr[1] ... arr[n-2]. If arr[i-1] is smaller  // than arr[n-1], and max ending with arr[n-1]  // needs to be updated, then update it  for (int i = 1; i < n; i++) {  res = _lis(arr, i, max_ref);  if (arr[i - 1] < arr[n - 1]  && res + 1>max_ending_here) max_ending_here = res + 1;  } // Porovnejte max_ending_here s celkovým // max. A v případě potřeby aktualizujte celkové maximum, pokud (*max_ref< max_ending_here)  *max_ref = max_ending_here;  // Return length of LIS ending with arr[n-1]  return max_ending_here; } // The wrapper function for _lis() int lis(int arr[], int n) {  // The max variable holds the result  int max = 1;  // The function _lis() stores its result in max  _lis(arr, n, &max);  // returns max  return max; } // Driver program to test above function int main() {  int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = sizeof(arr) / sizeof(arr[0]);  // Function call  printf('Length of lis is %d', lis(arr, n));  return 0; }>
Jáva
// A Naive Java Program for LIS Implementation import java.io.*; import java.util.*; class LIS {  // Stores the LIS  static int max_ref;  // To make use of recursive calls, this function must  // return two things: 1) Length of LIS ending with  // element arr[n-1]. We use max_ending_here for this  // purpose 2) Overall maximum as the LIS may end with an  // element before arr[n-1] max_ref is used this purpose.  // The value of LIS of full array of size n is stored in  // *max_ref which is our final result  static int _lis(int arr[], int n)  {  // Base case  if (n == 1)  return 1;  // 'max_ending_here' is length of LIS ending with  // arr[n-1]  int res, max_ending_here = 1;  // Recursively get all LIS ending with arr[0],  // arr[1] ... arr[n-2]. If arr[i-1] is smaller  // than arr[n-1], and max ending with arr[n-1] needs  // to be updated, then update it  for (int i = 1; i < n; i++) {  res = _lis(arr, i);  if (arr[i - 1] < arr[n - 1]  && res + 1>max_ending_here) max_ending_here = res + 1;  } // Porovnejte max_ending_here s celkovým max. A // v případě potřeby aktualizujte celkové maximum, pokud (max_ref< max_ending_here)  max_ref = max_ending_here;  // Return length of LIS ending with arr[n-1]  return max_ending_here;  }  // The wrapper function for _lis()  static int lis(int arr[], int n)  {  // The max variable holds the result  max_ref = 1;  // The function _lis() stores its result in max  _lis(arr, n);  // Returns max  return max_ref;  }  // Driver program to test above functions  public static void main(String args[])  {  int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = arr.length;  // Function call  System.out.println('Length of lis is '  + lis(arr, n));  } } // This code is contributed by Rajat Mishra>
Krajta
# A naive Python implementation of LIS problem # Global variable to store the maximum global maximum # To make use of recursive calls, this function must return # two things: # 1) Length of LIS ending with element arr[n-1]. We use # max_ending_here for this purpose # 2) Overall maximum as the LIS may end with an element # before arr[n-1] max_ref is used this purpose. # The value of LIS of full array of size n is stored in # *max_ref which is our final result def _lis(arr, n): # To allow the access of global variable global maximum # Base Case if n == 1: return 1 # maxEndingHere is the length of LIS ending with arr[n-1] maxEndingHere = 1 # Recursively get all LIS ending with # arr[0], arr[1]..arr[n-2] # If arr[i-1] is smaller than arr[n-1], and # max ending with arr[n-1] needs to be updated, # then update it for i in range(1, n): res = _lis(arr, i) if arr[i-1] < arr[n-1] and res+1>maxEndingHere: maxEndingHere = res + 1 # Porovnejte maxEndingHere s celkovým maximem. A # v případě potřeby aktualizujte celkové maximum maximum = max(maximum, maxEndingHere) return maxEndingHere def lis(arr): # Pro povolení přístupu globální proměnné globální maximum # Délka arr n = len(arr) # Maximální proměnná obsahuje výsledek maximum = 1 # Funkce _lis() ukládá svůj výsledek do maxima _lis(arr, n) return maximum # Program ovladače pro otestování výše uvedené funkce, pokud __name__ == '__main__': arr = [10, 22, 9, 33 , 21, 50, 41, 60] n = len(arr) # Volání funkce print('Délka lisu je', lis(arr)) # Tento kód přidal NIKHIL KUMAR SINGH>
C#
using System; // A Naive C# Program for LIS Implementation class LIS {  // Stores the LIS  static int max_ref;  // To make use of recursive calls, this function must  // return two things: 1) Length of LIS ending with  // element arr[n-1]. We use max_ending_here for this  // purpose 2) Overall maximum as the LIS may end with an  // element before arr[n-1] max_ref is used this purpose.  // The value of LIS of full array of size n is stored in  // *max_ref which is our final result  static int _lis(int[] arr, int n)  {  // Base case  if (n == 1)  return 1;  // 'max_ending_here' is length of LIS ending with  // arr[n-1]  int res, max_ending_here = 1;  // Recursively get all LIS ending with arr[0],  // arr[1] ... arr[n-2]. If arr[i-1] is smaller  // than arr[n-1], and max ending with arr[n-1] needs  // to be updated, then update it  for (int i = 1; i < n; i++) {  res = _lis(arr, i);  if (arr[i - 1] < arr[n - 1]  && res + 1>max_ending_here) max_ending_here = res + 1;  } // Porovnejte max_ending_here s celkovým maximem // a v případě potřeby aktualizujte celkové maximum, pokud (max_ref< max_ending_here)  max_ref = max_ending_here;  // Return length of LIS ending with arr[n-1]  return max_ending_here;  }  // The wrapper function for _lis()  static int lis(int[] arr, int n)  {  // The max variable holds the result  max_ref = 1;  // The function _lis() stores its result in max  _lis(arr, n);  // Returns max  return max_ref;  }  // Driver program to test above functions  public static void Main()  {  int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = arr.Length;  // Function call  Console.Write('Length of lis is ' + lis(arr, n)  + '
');  } }>
Javascript
>

Výstup
Length of lis is 5>

Časová náročnost: O(2n) Časová složitost tohoto rekurzivního přístupu je exponenciální, protože existuje případ překrývajících se dílčích problémů, jak je vysvětleno v rekurzivním stromovém diagramu výše.
Pomocný prostor: O(1). Pro ukládání hodnot se kromě vnitřního zásobníku nepoužívá žádný externí prostor.

Použití nejdelší rostoucí subsekvence Memorizace :

Pokud si toho všimneme pozorně, můžeme vidět, že výše uvedené rekurzivní řešení také následuje překrývající se dílčí problémy vlastnost, tj. stejná podstruktura řešená znovu a znovu v různých cestách rekurzního volání. Tomu se můžeme vyhnout pomocí memoizačního přístupu.

Vidíme, že každý stav lze jednoznačně identifikovat pomocí dvou parametrů:

  • Aktuální index (označuje poslední index LIS) a
  • Předchozí index (označuje koncový index předchozího LIS, za kterým je arr[i] je zřetězen).

Níže je uvedena implementace výše uvedeného přístupu.

příklad uživatelského jména
C++
// C++ code of memoization approach for LIS #include  using namespace std; // To make use of recursive calls, this // function must return two things: // 1) Length of LIS ending with element // arr[n-1]. // We use max_ending_here for this purpose // Overall maximum as the LIS may end with // an element before arr[n-1] max_ref is // used this purpose. // The value of LIS of full array of size // n is stored in *max_ref which is // our final result int f(int idx, int prev_idx, int n, int a[],  vector>& dp) { if (idx == n) { return 0;  } if (dp[idx][prev_idx + 1] != -1) { return dp[idx][prev_idx + 1];  } int notTake = 0 + f(idx + 1, předchozí_idx, n, a, dp);  int take = INT_MIN;  if (prev_idx == -1 || a[idx]> a[prev_idx]) { take = 1 + f(idx + 1, idx, n, a, dp);  } return dp[idx][prev_idx + 1] = max(take, notTake); } // Funkce pro zjištění délky // nejdelší rostoucí podsekvence int longestSubsequence(int n, int a[]) { vector> dp(n + 1, vektor (n + 1, -1));  return f(0, -1, n, a, dp); } // Program ovladače k ​​otestování výše uvedené funkce int main() { int a[] = { 3, 10, 2, 1, 20 };  int n = sizeof(a) / sizeof(a[0]);  // Volání funkce cout<< 'Length of lis is ' << longestSubsequence(n, a);  return 0; }>
Jáva
// A Memoization Java Program for LIS Implementation import java.lang.*; import java.util.Arrays; class LIS {  // To make use of recursive calls, this function must  // return two things: 1) Length of LIS ending with  // element arr[n-1]. We use max_ending_here for this  // purpose 2) Overall maximum as the LIS may end with an  // element before arr[n-1] max_ref is used this purpose.  // The value of LIS of full array of size n is stored in  // *max_ref which is our final result  static int f(int idx, int prev_idx, int n, int a[],  int[][] dp)  {  if (idx == n) {  return 0;  }  if (dp[idx][prev_idx + 1] != -1) {  return dp[idx][prev_idx + 1];  }  int notTake = 0 + f(idx + 1, prev_idx, n, a, dp);  int take = Integer.MIN_VALUE;  if (prev_idx == -1 || a[idx]>a[prev_idx]) { take = 1 + f(idx + 1, idx, n, a, dp);  } return dp[idx][prev_idx + 1] = Math.max(take, notTake);  } // Funkce wrapper pro _lis() static int lis(int arr[], int n) { // Funkce _lis() ukládá svůj výsledek do max int dp[][] = new int[n + 1][ n + 1];  for (int row[] : dp) Arrays.fill(row, -1);  return f(0, -1, n, arr, dp);  } // Ovladač pro testování výše uvedených funkcí public static void main(String args[]) { int a[] = { 3, 10, 2, 1, 20 };  int n = a.délka;  // Volání funkce System.out.println('Délka lisu je ' + lis(a, n));  } } // Tento kód přispěl Sanskar.>
Krajta
# A Naive Python recursive implementation # of LIS problem import sys # To make use of recursive calls, this # function must return two things: # 1) Length of LIS ending with element arr[n-1]. # We use max_ending_here for this purpose # 2) Overall maximum as the LIS may end with # an element before arr[n-1] max_ref is # used this purpose. # The value of LIS of full array of size n # is stored in *max_ref which is our final result def f(idx, prev_idx, n, a, dp): if (idx == n): return 0 if (dp[idx][prev_idx + 1] != -1): return dp[idx][prev_idx + 1] notTake = 0 + f(idx + 1, prev_idx, n, a, dp) take = -sys.maxsize - 1 if (prev_idx == -1 or a[idx]>a[prev_idx]): take = 1 + f(idx + 1, idx, n, a, dp) dp[idx][prev_idx + 1] = max(take, notTake) return dp[idx][prev_idx + 1] # Funkce pro nalezení délky nejdelší rostoucí # podsekvence. def longestSubsequence(n, a): dp = [[-1 for i in range(n + 1)]for j in range(n + 1)] return f(0, -1, n, a, dp) # Driver program, který otestuje výše uvedenou funkci, pokud __name__ == '__main__': a = [3, 10, 2, 1, 20] n = len(a) # Volání funkce print('Length of lis is', longestSubsequence( n, a)) # Tento kód přispěl shinjanpatra>
C#
// C# approach to implementation the memoization approach using System; class GFG {  // To make use of recursive calls, this  // function must return two things:  // 1) Length of LIS ending with element arr[n-1].  // We use max_ending_here for this purpose  // 2) Overall maximum as the LIS may end with  // an element before arr[n-1] max_ref is  // used this purpose.  // The value of LIS of full array of size n  // is stored in *max_ref which is our final result  public static int INT_MIN = -2147483648;  public static int f(int idx, int prev_idx, int n,  int[] a, int[, ] dp)  {  if (idx == n) {  return 0;  }  if (dp[idx, prev_idx + 1] != -1) {  return dp[idx, prev_idx + 1];  }  int notTake = 0 + f(idx + 1, prev_idx, n, a, dp);  int take = INT_MIN;  if (prev_idx == -1 || a[idx]>a[prev_idx]) { take = 1 + f(idx + 1, idx, n, a, dp);  } return dp[idx, prev_idx + 1] = Math.Max(take, notTake);  } // Funkce pro zjištění délky nejdelší rostoucí // podsekvence.  public static int longestSubsequence(int n, int[] a) { int[, ] dp = new int[n + 1, n + 1];  for (int i = 0; i< n + 1; i++) {  for (int j = 0; j < n + 1; j++) {  dp[i, j] = -1;  }  }  return f(0, -1, n, a, dp);  }  // Driver code  static void Main()  {  int[] a = { 3, 10, 2, 1, 20 };  int n = a.Length;  Console.WriteLine('Length of lis is '  + longestSubsequence(n, a));  } } // The code is contributed by Nidhi goel.>
Javascript
/* A Naive Javascript recursive implementation  of LIS problem */  /* To make use of recursive calls, this  function must return two things:  1) Length of LIS ending with element arr[n-1].  We use max_ending_here for this purpose  2) Overall maximum as the LIS may end with  an element before arr[n-1] max_ref is  used this purpose.  The value of LIS of full array of size n  is stored in *max_ref which is our final result  */  function f(idx, prev_idx, n, a, dp) {  if (idx == n) {  return 0;  }  if (dp[idx][prev_idx + 1] != -1) {  return dp[idx][prev_idx + 1];  }  var notTake = 0 + f(idx + 1, prev_idx, n, a, dp);  var take = Number.MIN_VALUE;  if (prev_idx == -1 || a[idx]>a[prev_idx]) { take = 1 + f(idx + 1, idx, n, a, dp);  } return (dp[idx][prev_idx + 1] = Math.max(take, notTake));  } // Funkce pro zjištění délky nejdelší rostoucí // podsekvence.  function longestSubsequence(n, a) { var dp = Array(n + 1) .fill() .map(() => Array(n + 1).fill(-1));  return f(0, -1, n, a, dp);  } /* Program ovladače k ​​otestování výše uvedené funkce */ var a = [3, 10, 2, 1, 20];  var n = 5;  console.log('Délka seznamu je ' + longestSubsequence(n, a));    // Tento kód přispěl satwiksuman.>

Výstup
Length of lis is 3>

Časová náročnost: NA2)
Pomocný prostor: NA2)

Použití nejdelší rostoucí subsekvence Dynamické programování :

Díky optimální substruktuře a překrývajícím se vlastnostem podproblémů můžeme k řešení problému využít i dynamické programování. Místo memoizace můžeme k implementaci rekurzivního vztahu použít vnořenou smyčku.

Vnější smyčka bude probíhat od i = 1 až N a vnitřní smyčka bude probíhat od j = 0 až i a k vyřešení problému použijte vztah opakování.

Níže je uvedena implementace výše uvedeného přístupu:

C++
// Dynamic Programming C++ implementation // of LIS problem #include  using namespace std; // lis() returns the length of the longest // increasing subsequence in arr[] of size n int lis(int arr[], int n) {  int lis[n];  lis[0] = 1;  // Compute optimized LIS values in  // bottom up manner  for (int i = 1; i < n; i++) {  lis[i] = 1;  for (int j = 0; j < i; j++)  if (arr[i]>arr[j] && lis[i]< lis[j] + 1)  lis[i] = lis[j] + 1;  }  // Return maximum value in lis[]  return *max_element(lis, lis + n); } // Driver program to test above function int main() {  int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = sizeof(arr) / sizeof(arr[0]);  // Function call  printf('Length of lis is %d
', lis(arr, n));  return 0; }>
Jáva
// Dynamic Programming Java implementation // of LIS problem import java.lang.*; class LIS {  // lis() returns the length of the longest  // increasing subsequence in arr[] of size n  static int lis(int arr[], int n)  {  int lis[] = new int[n];  int i, j, max = 0;  // Initialize LIS values for all indexes  for (i = 0; i < n; i++)  lis[i] = 1;  // Compute optimized LIS values in  // bottom up manner  for (i = 1; i < n; i++)  for (j = 0; j < i; j++)  if (arr[i]>arr[j] && lis[i]< lis[j] + 1)  lis[i] = lis[j] + 1;  // Pick maximum of all LIS values  for (i = 0; i < n; i++)  if (max < lis[i])  max = lis[i];  return max;  }  // Driver code  public static void main(String args[])  {  int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = arr.length;  // Function call  System.out.println('Length of lis is '  + lis(arr, n));  } } // This code is contributed by Rajat Mishra>
Krajta
# Dynamic programming Python implementation # of LIS problem # lis returns length of the longest # increasing subsequence in arr of size n def lis(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range(1, n): for j in range(0, i): if arr[i]>arr[j] a lis[i]< lis[j] + 1: lis[i] = lis[j]+1 # Initialize maximum to 0 to get # the maximum of all LIS maximum = 0 # Pick maximum of all LIS values for i in range(n): maximum = max(maximum, lis[i]) return maximum # Driver program to test above function if __name__ == '__main__': arr = [10, 22, 9, 33, 21, 50, 41, 60] print('Length of lis is', lis(arr)) # This code is contributed by Nikhil Kumar Singh>
C#
// Dynamic Programming C# implementation of LIS problem using System; class LIS {  // lis() returns the length of the longest increasing  // subsequence in arr[] of size n  static int lis(int[] arr, int n)  {  int[] lis = new int[n];  int i, j, max = 0;  // Initialize LIS values for all indexes  for (i = 0; i < n; i++)  lis[i] = 1;  // Compute optimized LIS values in bottom up manner  for (i = 1; i < n; i++)  for (j = 0; j < i; j++)  if (arr[i]>arr[j] && lis[i]< lis[j] + 1)  lis[i] = lis[j] + 1;  // Pick maximum of all LIS values  for (i = 0; i < n; i++)  if (max < lis[i])  max = lis[i];  return max;  }  // Driver code  public static void Main()  {  int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 };  int n = arr.Length;  // Function call  Console.WriteLine('Length of lis is '  + lis(arr, n));  } } // This code is contributed by Ryuga>
Javascript
>

Výstup
Length of lis is 5>

Časová náročnost: NA2) Jako vnořená smyčka se používá.
Pomocný prostor: O(N) Použití libovolného pole k uložení hodnot LIS v každém indexu.

Poznámka: Časová složitost výše uvedeného řešení dynamického programování (DP) je O(n^2), ale existuje O(N* logN) roztok pro problém LIS. O(N log N) řešení jsme zde nediskutovali.
Odkaz: Nejdelší rostoucí velikost podsekvence (N * logN) pro zmíněný přístup.