Array element moved by k using single moves | Java 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 program to test the above function
import java . io . * ; class GFG { static int winner ( int a [ ] , int n , int k ) { if ( k >= n - 1 ) return n ; int best = 0 , times = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > best ) { best = a [ i ] ; if ( i == 1 ) times = 1 ; } else times += 1 ; if ( times >= k ) return best ; } return best ; } public static void main ( String args [ ] ) { int a [ ] = { 2 , 1 , 3 , 4 , 5 } ; int n = a . length ; int k = 2 ; System . out . println ( winner ( a , n , k ) ) ; } }