Array element moved by k using single moves | C ++ 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 ; times = 1 ; no of wins is 1 now ; 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
#include <iostream> NEW_LINE using namespace std ; 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 ) } else if ( times >= k ) return best ; } return best ; } int main ( ) { int a [ ] = { 2 , 1 , 3 , 4 , 5 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 2 ; cout << winner ( a , n , k ) ; return 0 ; }