Count ways to reach a score using 1 and 2 with no consecutive 2 s | Bottom up approach for counting ways to reach a score using 1 and 2 with consecutive 2 allowed ; noOfWays [ i ] will store count for last 3 values before i . ; Loop till " n + 1" to compute value for " n " ; number of ways if first run is 1 ; number of ways if first run is 2 and second run is 1 ; Remember last 3 values ; Driver code
function CountWays ( n ) { var noOfWays = Array ( 3 ) . fill ( 0 ) ; noOfWays [ 0 ] = 1 ; noOfWays [ 1 ] = 1 ; noOfWays [ 2 ] = 1 + 1 ; for ( var i = 3 ; i < n + 1 ; i ++ ) { noOfWays [ i ] = noOfWays [ 3 - 1 ] + noOfWays [ 3 - 3 ] ; noOfWays [ 0 ] = noOfWays [ 1 ] ; noOfWays [ 1 ] = noOfWays [ 2 ] ; noOfWays [ 2 ] = noOfWays [ i ] ; } return noOfWays [ n ] ; } var n = 5 ; document . write ( CountWays ( n ) ) ;