Dané pole arr[] veľkosti N , úlohou je nájsť dĺžku najdlhšej rastúcej podsekvencie (LIS), t.j. najdlhšej možnej podsekvencie, v ktorej sú prvky podsekvencie zoradené v rastúcom poradí.

Najdlhšia rastúca následná sekvencia
Príklady:
Vstup: arr[] = {3, 10, 2, 1, 20}
Výkon: 3
Vysvetlenie: Najdlhšia rastúca podsekvencia je 3, 10, 20javascript onclickVstup: arr[] = {50, 3, 10, 7, 40, 80}
Výkon: 4
Vysvetlenie: Najdlhšia rastúca podsekvencia je {3, 7, 40, 80}
Vstup: arr[] = {30, 20, 10}
Výkon: 1
Vysvetlenie: Najdlhšie rastúce podsekvencie sú {30}, {20} a (10)Vstup: arr[] = {10, 20, 35, 80}
Výkon: 4
Vysvetlenie: Celé pole je zoradené
Použitie najdlhšej rastúcej sekvencie Rekurzia :
Myšlienka prejsť vstupným poľom zľava doprava a nájsť dĺžku najdlhšej rastúcej subsekvencie (LIS) končiacu každým prvkom arr[i]. Nech nájdená dĺžka pre arr[i] je L[i]. Na konci vrátime maximum zo všetkých hodnôt L[i]. Teraz vyvstáva otázka, ako vypočítame L[i]? Na tento účel použijeme rekurziu, zvážime všetky menšie prvky naľavo od arr[i], rekurzívne vypočítame hodnotu LIS pre všetky menšie prvky naľavo, vezmeme maximum zo všetkých a pridáme k tomu 1. Ak naľavo od prvku nie je žiadny menší prvok, vrátime 1.
Nechaj L(i) byť dĺžka LIS končiaca na indexe i tak, že arr[i] je posledným prvkom LIS. Potom L(i) možno rekurzívne zapísať ako:
- L(i) = 1 + max(L(j)), kde 0
- L(i) = 1, ak také j neexistuje.
Formálne dĺžka LIS končiaca na indexe i , je o 1 väčšia ako maximum dĺžok všetkých LIS končiacich na nejakom indexe j také že arr[j]
kde j .
Vidíme, že vyššie uvedený vzťah opakovania nasleduje po optimálna spodná konštrukcia nehnuteľnosť.
Ilustrácia:
Pre lepšie pochopenie postupujte podľa nasledujúceho obrázku:
Zvážte arr[] = {3, 10, 2, 11}
L(i): Označuje LIS podpola končiaceho na pozícii „i“
Rekurzný strom
Pri implementácii vyššie uvedenej myšlienky postupujte podľa krokov uvedených nižšie:
- Vytvorte rekurzívnu funkciu.
- Pre každé rekurzívne volanie Iterujte z i = 1 na aktuálnu pozíciu a vykonajte nasledovné:
- Nájdite možnú dĺžku najdlhšej rastúcej podsekvencie končiacej na aktuálnej pozícii, ak predchádzajúca sekvencia skončila na i .
- Podľa toho aktualizujte maximálnu možnú dĺžku.
- Opakujte to pre všetky indexy a nájdite odpoveď
Nižšie je uvedená implementácia rekurzívneho prístupu:
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; } // Porovnajte max_ending_here s // celkovým max. A v prípade potreby aktualizujte // celkové maximum, ak (*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; } // Porovnajte max_ending_here s celkovým // max. V prípade potreby aktualizujte celkové maximum, ak (*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; }>
Java // 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; } // Porovnajte max_ending_here s celkovým max. A // v prípade potreby aktualizujte celkové maximum, ak (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>
Python # 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 # Porovnajte maxEndingHere s celkovým maximom. A # v prípade potreby aktualizujte celkové maximum maximum = max(maximum, maxEndingHere) return maxEndingHere def lis(arr): # Umožnenie prístupu globálnej premennej globálne maximum # Dĺžka arr n = len(arr) # Maximálna premenná obsahuje výsledok maximum = 1 # Funkcia _lis() uloží svoj výsledok do maxima _lis(arr, n) vráti maximum # Program ovládača na testovanie vyššie uvedenej funkcie, ak __name__ == '__main__': arr = [10, 22, 9, 33 , 21, 50, 41, 60] n = len(arr) # Volanie funkcie print('Dĺžka lisu je', lis(arr)) # Tento kód prispel 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; } // Porovnajte max_ending_here s celkovým maximom // a v prípade potreby aktualizujte celkové maximum, ak (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ýkon
Length of lis is 5>
Časová zložitosť: O(2n) Časová zložitosť tohto rekurzívneho prístupu je exponenciálna, pretože existuje prípad prekrývajúcich sa čiastkových problémov, ako je vysvetlené v schéme rekurzívneho stromu vyššie.
Pomocný priestor: O(1). Na ukladanie hodnôt sa nepoužíva žiadny externý priestor okrem vnútorného priestoru zásobníka.
Najdlhšia rastúca subsekvencia pomocou Zapamätanie :
Ak si všimneme pozorne, môžeme vidieť, že vyššie uvedené rekurzívne riešenie tiež nasleduje prekrývajúce sa čiastkové problémy vlastnosť, t.j. rovnaká subštruktúra vyriešená znova a znova v rôznych cestách rekurzného volania. Tomu sa môžeme vyhnúť pomocou memoizačného prístupu.
ukážkový java kódVidíme, že každý stav možno jednoznačne identifikovať pomocou dvoch parametrov:
- Aktuálny index (označuje posledný index LIS) a
- Predchádzajúci index (označuje koncový index predchádzajúceho LIS, za ktorým je arr[i] sa spája).
Nižšie je uvedená implementácia vyššie uvedeného prístupu.
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, 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] = max(take, notTake); } // Funkcia na nájdenie dĺžky // najdlhšej rastúcej podsekvencie int longestSubsequence(int n, int a[]) { vector> dp(n + 1, vektor (n + 1, -1)); návrat f(0, -1, n, a, dp); } // Program ovládača na testovanie funkcie vyššie int main() { int a[] = { 3, 10, 2, 1, 20 }; int n = veľkosť(a) / veľkosť(a[0]); // Volanie funkcie cout<< 'Length of lis is ' << longestSubsequence(n, a); return 0; }>
Java // 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); } // Funkcia wrapper pre _lis() static int lis(int arr[], int n) { // Funkcia _lis() uloží svoj výsledok do max int dp[][] = new int[n + 1][ n + 1]; for (int row[] : dp) Arrays.fill(row, -1); návrat f(0, -1, n, arr, dp); } // Program ovládača na testovanie vyššie uvedených funkcií public static void main(String args[]) { int a[] = { 3, 10, 2, 1, 20 }; int n = a.dĺžka; // Volanie funkcie System.out.println('Dlzka lisu je ' + lis(a, n)); } } // Tento kód pridal Sanskar.>
Python # 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] # Funkcia na nájdenie dĺžky najdlhšej rastúcej # podsekvencie. 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 na otestovanie vyššie uvedenej funkcie, ak __name__ == '__main__': a = [3, 10, 2, 1, 20] n = len(a) # Volanie funkcie print('Dĺžka zoznamu je', longestSubsequence( n, a)) # Tento kód prispel 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); } // Funkcia na nájdenie dĺžky najdlhšej rastúcej // podsekvencie. public static int longestSubsequence(int n, int[] a) { int[, ] dp = new int[n + 1, n + 1]; pre (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)); } // Funkcia na nájdenie dĺžky najdlhšej rastúcej // podsekvencie. function longestSubsequence(n, a) { var dp = Array(n + 1) .fill() .map(() => Array(n + 1).fill(-1)); návrat f(0, -1, n, a, dp); } /* Program ovládača na testovanie vyššie uvedenej funkcie */ var a = [3, 10, 2, 1, 20]; var n = 5; console.log('Dlzka zoznamu je ' + longestSubsequence(n, a)); // Tento kód pridal satwiksuman.>
Výkon
Length of lis is 3>
Časová zložitosť: O(N2)
Pomocný priestor: O(N2)
Najdlhšia rastúca subsekvencia pomocou Dynamické programovanie :
Vďaka optimálnej subštruktúre a vlastnostiam prekrývajúcich sa podproblémov môžeme na riešenie problému využiť aj dynamické programovanie. Namiesto memoizácie môžeme použiť vnorenú slučku na implementáciu rekurzívneho vzťahu.
Vonkajšia slučka bude prebiehať od i = 1 až N a vnútorná slučka bude prebiehať z j = 0 až i a použiť rekurentný vzťah na vyriešenie problému.
Nižšie je uvedená implementácia vyššie uvedeného prí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; }>
Java // 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>
Python # 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ýkon
Length of lis is 5>
Časová zložitosť: O(N2) Ako vnorená slučka sa používa.
Pomocný priestor: O(N) Použitie ľubovoľného poľa na uloženie hodnôt LIS pri každom indexe.
Poznámka: Časová zložitosť vyššie uvedeného riešenia dynamického programovania (DP) je O(n^2), ale existuje O(N* logN) roztok pre problém LIS. Nehovorili sme tu o riešení O(N log N).
Pozri: Veľkosť najdlhšej rastúcej subsekvencie (N * logN) pre spomínaný prístup.