Array element moved by k using single moves | Javascript program to find winner of game ; If the number of steps is more then n - 1 , ; Initially the best is 0 and no of wins is 0. ; Traverse through all the numbers ; If the value of array is more then that of previous best ; best is replaced by a [ i ] ; If not the first index ; No of wins is 1 now ; If it wins ; If any position has more then k wins then return ; Maximum element will be winner because we move smaller element at end and repeat the process . ; Driver code
function winner ( a , n , k ) { if ( k >= n - 1 ) return n ; let best = 0 , times = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] > best ) { best = a [ i ] ; if ( i ) times = 1 ; } else times += 1 ; if ( times >= k ) return best ; } return best ; } let a = [ 2 , 1 , 3 , 4 , 5 ] ; let n = a . length ; let k = 2 ; document . write ( winner ( a , n , k ) ) ;