Una successione {X1 X2 .. Xn} è una successione alternata se i suoi elementi soddisfano una delle seguenti relazioni:
X1< X2 >X3< X4 >X5< …. xn or
X1 > X2< X3 >X4< X5 >…. xnn
Esempi:
Pratica consigliata Sottosequenza alternata più lunga Provalo!Ingresso: arr[] = {1 5 4}
Produzione: 3
Spiegazione: L'intero array ha la forma x1< x2 >x3Ingresso: arr[] = {10 22 9 33 49 50 31 60}
Produzione: 6
Spiegazione: Le sottosequenze {10 22 9 33 31 60} o
{10 22 9 49 31 60} o {10 22 9 50 31 60}
sono la sottosequenza più lunga di lunghezza 6
Nota: Questo problema è un'estensione di problema della sottosequenza crescente più lunga ma richiede una riflessione maggiore per trovare la proprietà ottimale della sottostruttura in questo
Utilizzo della sottosequenza alternata più lunga programmazione dinamica :
Per risolvere il problema seguire l'idea seguente:
Risolveremo questo problema con il metodo di programmazione dinamica poiché ha una sottostruttura ottimale e sottoproblemi sovrapposti
sistema operativo Linux
Seguire i passaggi seguenti per risolvere il problema:
- Sia dato ad A un array di lunghezza N
- Definiamo un array 2D las[n][2] tale che las[i][0] contenga la sottosequenza alternata più lunga che termina con l'indice i e l'ultimo elemento sia maggiore del suo elemento precedente
- las[i][1] contiene la sottosequenza alternata più lunga che termina con l'indice i e l'ultimo elemento è più piccolo del suo elemento precedente, quindi abbiamo la seguente relazione di ricorrenza tra loro
las[i][0] = Lunghezza della sottosequenza alternata più lunga
che termina con l'indice i e l'ultimo elemento è maggiore
rispetto al suo elemento precedentetasti modificatoriil[i] [1] = Lunghezza della sottosequenza alternata più lunga
che termina con l'indice i e l'ultimo elemento è più piccolo
rispetto al suo elemento precedenteFormulazione ricorsiva:
las[i][0] = max (las[i][0] las[j][1] + 1);
per tutti j< i and A[j] < A[i]las[i][1] = max (las[i][1] las[j][0] + 1);
per tutti j< i and A[j] >A[i]
- La prima relazione di ricorrenza si basa sul fatto che se siamo nella posizione i e questo elemento deve essere più grande del suo elemento precedente, allora affinché questa sequenza (fino a i) sia più grande proveremo a scegliere un elemento j (< i) such that A[j] < A[i] i.e. A[j] can become A[i]’s previous element and las[j][1] + 1 is bigger than las[i][0] then we will update las[i][0].
- Ricorda che abbiamo scelto las[j][1] + 1 non las[j][0] + 1 per soddisfare la proprietà alternativa perché in las[j][0] l'ultimo elemento è più grande del precedente e A[i] è maggiore di A[j] il che interromperà la proprietà alternata se aggiorniamo. Quindi sopra i fatti deriva la prima relazione di ricorrenza, un argomento simile può essere fatto anche per la seconda relazione di ricorrenza.
Di seguito è riportata l’implementazione dell’approccio di cui sopra:
C++// C++ program to find longest alternating // subsequence in an array #include using namespace std; // Function to return max of two numbers int max(int a int b) { return (a > b) ? a : b; } // Function to return longest alternating // subsequence length int zzis(int arr[] int n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; // Initialize all values from 1 for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; // Initialize result int res = 1; // Compute values in bottom up manner for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller then // check with las[j][0] if (arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } // Pick maximum of both values at index i if (res < max(las[i][0] las[i][1])) res = max(las[i][0] las[i][1]); } return res; } // Driver code int main() { int arr[] = { 10 22 9 33 49 50 31 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << 'Length of Longest alternating ' << 'subsequence is ' << zzis(arr n); return 0; } // This code is contributed by shivanisinghss2110
C // C program to find longest alternating subsequence in // an array #include #include // function to return max of two numbers int max(int a int b) { return (a > b) ? a : b; } // Function to return longest alternating subsequence length int zzis(int arr[] int n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater then check with // las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller then check with // las[j][0] if (arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(las[i][0] las[i][1])) res = max(las[i][0] las[i][1]); } return res; } /* Driver code */ int main() { int arr[] = { 10 22 9 33 49 50 31 60 }; int n = sizeof(arr) / sizeof(arr[0]); printf( 'Length of Longest alternating subsequence is %dn' zzis(arr n)); return 0; }
Java // Java program to find longest // alternating subsequence in an array import java.io.*; class GFG { // Function to return longest // alternating subsequence length static int zzis(int arr[] int n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[][] = new int[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i][0] = las[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller then // check with las[j][0] if (arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0] las[i][1])) res = Math.max(las[i][0] las[i][1]); } return res; } /* Driver code*/ public static void main(String[] args) { int arr[] = { 10 22 9 33 49 50 31 60 }; int n = arr.length; System.out.println('Length of Longest ' + 'alternating subsequence is ' + zzis(arr n)); } } // This code is contributed by Prerna Saini
Python3 # Python3 program to find longest # alternating subsequence in an array # Function to return max of two numbers def Max(a b): if a > b: return a else: return b # Function to return longest alternating # subsequence length def zzis(arr n): '''las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element''' las = [[0 for i in range(2)] for j in range(n)] # Initialize all values from 1 for i in range(n): las[i][0] las[i][1] = 1 1 # Initialize result res = 1 # Compute values in bottom up manner for i in range(1 n): # Consider all elements as # previous of arr[i] for j in range(0 i): # If arr[i] is greater then # check with las[j][1] if (arr[j] < arr[i] and las[i][0] < las[j][1] + 1): las[i][0] = las[j][1] + 1 # If arr[i] is smaller then # check with las[j][0] if(arr[j] > arr[i] and las[i][1] < las[j][0] + 1): las[i][1] = las[j][0] + 1 # Pick maximum of both values at index i if (res < max(las[i][0] las[i][1])): res = max(las[i][0] las[i][1]) return res # Driver Code arr = [10 22 9 33 49 50 31 60] n = len(arr) print('Length of Longest alternating subsequence is' zzis(arr n)) # This code is contributed by divyesh072019
C# // C# program to find longest // alternating subsequence // in an array using System; class GFG { // Function to return longest // alternating subsequence length static int zzis(int[] arr int n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int[ ] las = new int[n 2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) las[i 0] = las[i 1] = 1; // Initialize result int res = 1; /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater then // check with las[j][1] if (arr[j] < arr[i] && las[i 0] < las[j 1] + 1) las[i 0] = las[j 1] + 1; // If arr[i] is smaller then // check with las[j][0] if (arr[j] > arr[i] && las[i 1] < las[j 0] + 1) las[i 1] = las[j 0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.Max(las[i 0] las[i 1])) res = Math.Max(las[i 0] las[i 1]); } return res; } // Driver Code public static void Main() { int[] arr = { 10 22 9 33 49 50 31 60 }; int n = arr.Length; Console.WriteLine('Length of Longest ' + 'alternating subsequence is ' + zzis(arr n)); } } // This code is contributed by anuj_67.
PHP // PHP program to find longest // alternating subsequence in // an array // Function to return longest // alternating subsequence length function zzis($arr $n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ $las = array(array()); /* Initialize all values from 1 */ for ( $i = 0; $i < $n; $i++) $las[$i][0] = $las[$i][1] = 1; $res = 1; // Initialize result /* Compute values in bottom up manner */ for ( $i = 1; $i < $n; $i++) { // Consider all elements // as previous of arr[i] for ($j = 0; $j < $i; $j++) { // If arr[i] is greater then // check with las[j][1] if ($arr[$j] < $arr[$i] and $las[$i][0] < $las[$j][1] + 1) $las[$i][0] = $las[$j][1] + 1; // If arr[i] is smaller then // check with las[j][0] if($arr[$j] > $arr[$i] and $las[$i][1] < $las[$j][0] + 1) $las[$i][1] = $las[$j][0] + 1; } /* Pick maximum of both values at index i */ if ($res < max($las[$i][0] $las[$i][1])) $res = max($las[$i][0] $las[$i][1]); } return $res; } // Driver Code $arr = array(10 22 9 33 49 50 31 60 ); $n = count($arr); echo 'Length of Longest alternating ' . 'subsequence is ' zzis($arr $n) ; // This code is contributed by anuj_67. ?> JavaScript <script> // Javascript program to find longest // alternating subsequence in an array // Function to return longest // alternating subsequence length function zzis(arr n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ let las = new Array(n); for (let i = 0; i < n; i++) { las[i] = new Array(2); for (let j = 0; j < 2; j++) { las[i][j] = 0; } } /* Initialize all values from 1 */ for (let i = 0; i < n; i++) las[i][0] = las[i][1] = 1; let res = 1; // Initialize result /* Compute values in bottom up manner */ for (let i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (let j = 0; j < i; j++) { // If arr[i] is greater then // check with las[j][1] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) las[i][0] = las[j][1] + 1; // If arr[i] is smaller then // check with las[j][0] if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1) las[i][1] = las[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][0] las[i][1])) res = Math.max(las[i][0] las[i][1]); } return res; } let arr = [ 10 22 9 33 49 50 31 60 ]; let n = arr.length; document.write('Length of Longest '+ 'alternating subsequence is ' + zzis(arr n)); // This code is contributed by rameshtravel07. </script>
Produzione
Length of Longest alternating subsequence is 6
Complessità temporale: SU2)
Spazio ausiliario: O(N) poiché è stato occupato N spazio aggiuntivo
Approccio efficiente: Per risolvere il problema seguire l'idea seguente:
Nell'approccio di cui sopra in qualsiasi momento teniamo traccia di due valori (la lunghezza della sottosequenza alternata più lunga che termina con l'indice i e l'ultimo elemento è inferiore o maggiore dell'elemento precedente) per ogni elemento dell'array. Per ottimizzare lo spazio dobbiamo memorizzare solo due variabili per elemento in qualsiasi indice i
inc = Lunghezza della sottosequenza alternativa più lunga finora con il valore corrente maggiore del valore precedente.
dec = Lunghezza della sottosequenza alternativa più lunga finora con il valore corrente inferiore al valore precedente.
La parte difficile di questo approccio è aggiornare questi due valori.quadro primaverile'inc' dovrebbe essere aumentato se e solo se l'ultimo elemento nella sequenza alternativa era più piccolo dell'elemento precedente.
'dec' dovrebbe essere aumentato se e solo se l'ultimo elemento nella sequenza alternativa era maggiore del suo elemento precedente.
Seguire i passaggi seguenti per risolvere il problema:
- Dichiara due numeri interi inc e dec uguali a uno
- Esegui un ciclo per i [1 N-1]
- Se arr[i] è maggiore dell'elemento precedente, impostare inc uguale a dec + 1
- Altrimenti se arr[i] è più piccolo dell'elemento precedente, imposta dec uguale a inc + 1
- Restituisce il massimo di inc e dec
Di seguito è riportata l’implementazione dell’approccio di cui sopra:
C++// C++ program for above approach #include using namespace std; // Function for finding // longest alternating // subsequence int LAS(int arr[] int n) { // 'inc' and 'dec' initialized as 1 // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // 'inc' changes if 'dec' // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // 'dec' changes if 'inc' // changes dec = inc + 1; } } // Return the maximum length return max(inc dec); } // Driver Code int main() { int arr[] = { 10 22 9 33 49 50 31 60 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call cout << LAS(arr n) << endl; return 0; }
Java // Java Program for above approach public class GFG { // Function for finding // longest alternating // subsequence static int LAS(int[] arr int n) { // 'inc' and 'dec' initialized as 1 // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // 'inc' changes if 'dec' // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // 'dec' changes if 'inc' // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc dec); } // Driver Code public static void main(String[] args) { int[] arr = { 10 22 9 33 49 50 31 60 }; int n = arr.length; // Function Call System.out.println(LAS(arr n)); } }
Python3 # Python3 program for above approach def LAS(arr n): # 'inc' and 'dec' initialized as 1 # as single element is still LAS inc = 1 dec = 1 # Iterate from second element for i in range(1 n): if (arr[i] > arr[i-1]): # 'inc' changes if 'dec' # changes inc = dec + 1 elif (arr[i] < arr[i-1]): # 'dec' changes if 'inc' # changes dec = inc + 1 # Return the maximum length return max(inc dec) # Driver Code if __name__ == '__main__': arr = [10 22 9 33 49 50 31 60] n = len(arr) # Function Call print(LAS(arr n))
C# // C# program for above approach using System; class GFG { // Function for finding // longest alternating // subsequence static int LAS(int[] arr int n) { // 'inc' and 'dec' initialized as 1 // as single element is still LAS int inc = 1; int dec = 1; // Iterate from second element for (int i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // 'inc' changes if 'dec' // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // 'dec' changes if 'inc' // changes dec = inc + 1; } } // Return the maximum length return Math.Max(inc dec); } // Driver code static void Main() { int[] arr = { 10 22 9 33 49 50 31 60 }; int n = arr.Length; // Function Call Console.WriteLine(LAS(arr n)); } } // This code is contributed by divyeshrabadiya07
JavaScript <script> // Javascript program for above approach // Function for finding // longest alternating // subsequence function LAS(arr n) { // 'inc' and 'dec' initialized as 1 // as single element is still LAS let inc = 1; let dec = 1; // Iterate from second element for (let i = 1; i < n; i++) { if (arr[i] > arr[i - 1]) { // 'inc' changes if 'dec' // changes inc = dec + 1; } else if (arr[i] < arr[i - 1]) { // 'dec' changes if 'inc' // changes dec = inc + 1; } } // Return the maximum length return Math.max(inc dec); } let arr = [ 10 22 9 33 49 50 31 60 ]; let n = arr.length; // Function Call document.write(LAS(arr n)); // This code is contributed by mukesh07. </script>
Produzione:
6
Complessità temporale: SU)
Spazio ausiliario: O(1)
Crea quiz