Steps required to visit M points in order on a circular ring of N points | Function to count the steps required ; Start at 1 ; Initialize steps ; If nxt is greater than cur ; Now we are at a [ i ] ; Driver code
function findSteps ( n , m , a ) { var cur = 1 ; var steps = 0 ; for ( var i = 0 ; i < m ; i ++ ) { if ( a [ i ] >= cur ) steps += ( a [ i ] - cur ) ; else steps += ( n - cur + a [ i ] ) ; cur = a [ i ] ; } return steps ; } var n = 3 , m = 3 ; var a = [ 2 , 1 , 2 ] ; document . write ( findSteps ( n , m , a ) ) ;