Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times | Java Program for the above approach ; Function to count number of sequences satisfying the given criteria ; Stores the index of the last occurrence of the element ; Initialize an array to store the number of different sequences that are possible of length i ; Base Case ; If no operation is applied on ith element ; If operation is applied on ith element ; Update the last occurrence of curEle ; Finally , print the answer
import java . io . * ; class GFG { static void countPossiblities ( int arr [ ] , int n ) { int [ ] lastOccur = new int [ 100000 ] ; for ( int i = 0 ; i < n ; i ++ ) { lastOccur [ i ] = - 1 ; } int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { int curEle = arr [ i - 1 ] ; dp [ i ] = dp [ i - 1 ] ; if ( lastOccur [ curEle ] != - 1 & lastOccur [ curEle ] < i - 1 ) { dp [ i ] += dp [ lastOccur [ curEle ] ] ; } lastOccur [ curEle ] = i ; } System . out . println ( dp [ n ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 2 , 2 } ; int N = arr . length ; countPossiblities ( arr , N ) ; } }