Count all N | Function to print the count of arrays satisfying given condition ; First element of array is set as 1 ; Since the first element of arr [ ] is 1 , the second element can 't be 1 ; Traverse the remaining indices ; If arr [ i ] = 1 ; If arr [ i ] a 1 ; Since last element needs to be 1 ; Driver Code ; Stores the count of arrays where arr [ 0 ] = arr [ N - 1 ] = 1 ; Since arr [ 0 ] and arr [ N - 1 ] can be any number from 1 to M ; Print answer
function totalArrays ( N , M ) { var end_with_one = Array ( N + 1 ) ; var end_not_with_one = Array ( N + 1 ) ; end_with_one [ 0 ] = 1 ; end_not_with_one [ 0 ] = 0 ; end_with_one [ 1 ] = 0 ; end_not_with_one [ 1 ] = M - 1 ; for ( var i = 2 ; i < N ; i ++ ) { end_with_one [ i ] = end_not_with_one [ i - 1 ] ; end_not_with_one [ i ] = end_with_one [ i - 1 ] * ( M - 1 ) + end_not_with_one [ i - 1 ] * ( M - 2 ) ; } return end_with_one [ N - 1 ] ; } var N = 3 , M = 3 ; var temp = totalArrays ( N , M ) ; var ans = M * temp ; document . write ( ans + " " ) ;