Skip to content

Commit 447c5fa

Browse files
authored
Add Longest Alternating Subsequence (TheAlgorithms#2743)
1 parent 9ff553e commit 447c5fa

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
3+
* Problem Statement: -
4+
* Find Longest Alternating Subsequence
5+
6+
* A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations :
7+
8+
x1 < x2 > x3 < x4 > x5 < …. xn or
9+
x1 > x2 < x3 > x4 < x5 > …. xn
10+
*/
11+
12+
import java.io.*;
13+
14+
public class LongestAlternatingSubsequence {
15+
16+
/* Function to return longest alternating subsequence length*/
17+
static int AlternatingLength(int arr[], int n){
18+
/*
19+
20+
las[i][0] = Length of the longest
21+
alternating subsequence ending at
22+
index i and last element is
23+
greater than its previous element
24+
25+
las[i][1] = Length of the longest
26+
alternating subsequence ending at
27+
index i and last element is
28+
smaller than its previous
29+
element
30+
31+
*/
32+
int las[][] = new int[n][2]; // las = LongestAlternatingSubsequence
33+
34+
for (int i = 0; i < n; i++)
35+
las[i][0] = las[i][1] = 1;
36+
37+
int result = 1; // Initialize result
38+
39+
/* Compute values in bottom up manner */
40+
for (int i = 1; i < n; i++){
41+
42+
/* Consider all elements as previous of arr[i]*/
43+
for (int j = 0; j < i; j++){
44+
45+
/* If arr[i] is greater, then check with las[j][1] */
46+
if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1)
47+
las[i][0] = las[j][1] + 1;
48+
49+
/* If arr[i] is smaller, then check with las[j][0]*/
50+
if( arr[j] > arr[i] && las[i][1] < las[j][0] + 1)
51+
las[i][1] = las[j][0] + 1;
52+
}
53+
54+
/* Pick maximum of both values at index i */
55+
if (result < Math.max(las[i][0], las[i][1]))
56+
result = Math.max(las[i][0], las[i][1]);
57+
}
58+
59+
return result;
60+
}
61+
62+
public static void main(String[] args)
63+
{
64+
int arr[] = { 10, 22, 9, 33, 49,50, 31, 60 };
65+
int n = arr.length;
66+
System.out.println("Length of Longest "+"alternating subsequence is " +AlternatingLength(arr, n));
67+
}
68+
}

0 commit comments

Comments
 (0)