1+ import java .util .Arrays ;
2+
3+ public final class LongestAlternatingSubsequence {
4+ private LongestAlternatingSubsequence () {
5+ }
6+
7+ static int alternatingLength (int [] arr , int n ) {
8+ if (n == 0 ) {
9+ return 0 ;
10+ }
11+
12+ int [][] las = new int [n ][2 ];
13+
14+ for (int i = 0 ; i < n ; i ++) {
15+ las [i ][0 ] = 1 ;
16+ las [i ][1 ] = 1 ;
17+ }
18+
19+ int result = 1 ;
20+
21+ for (int i = 1 ; i < n ; i ++) {
22+ for (int j = 0 ; j < i ; j ++) {
23+ if (arr [j ] < arr [i ] && las [i ][0 ] < las [j ][1 ] + 1 ) {
24+ las [i ][0 ] = las [j ][1 ] + 1 ;
25+ }
26+
27+ if (arr [j ] > arr [i ] && las [i ][1 ] < las [j ][0 ] + 1 ) {
28+ las [i ][1 ] = las [j ][0 ] + 1 ;
29+ }
30+ }
31+ result = Math .max (result , Math .max (las [i ][0 ], las [i ][1 ]));
32+ }
33+ return result ;
34+ }
35+
36+ public static void main (String [] args ) {
37+ int [] arr1 = {10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 };
38+ int length1 = alternatingLength (arr1 , arr1 .length );
39+ System .out .println ("Array: " + Arrays .toString (arr1 ));
40+ System .out .println ("Length of the longest alternating subsequence is: " + length1 );
41+
42+ System .out .println ("\n ----------------------------------------\n " );
43+
44+ int [] arr2 = {1 , 5 , 4 , 8 , 2 , 7 , 3 };
45+ int length2 = alternatingLength (arr2 , arr2 .length );
46+ System .out .println ("Array: " + Arrays .toString (arr2 ));
47+ System .out .println ("Length of the longest alternating subsequence is: " + length2 );
48+ }
49+ }
0 commit comments