Monday, May 20, 2024

 Given an integer array arr of distinct integers and an integer k.


A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.


Return the integer which will win the game.


It is guaranteed that there will be a winner of the game.

class Solution {

    public int getWinner(int[] arr, int k) {

        int win = 0;

        if (arr == null || arr.length < 2) { return Integer.MIN_VALUE; }

        if (k > arr.length){ 

            int max = Integer.MIN_VALUE;

            for (int i = 0; i < arr.length; i++) {

                if (arr[i] > max) {

                    max = arr[i];

                }

                return max;

            }

        }

        for (int i = 0; i < arr.length * arr.length; i++) {

            if (win >= k) { 

                break; 

            } 

            if (arr[0] > arr[1]) {

                win++;

                int temp = arr[1];

                for (int j = 2; j < arr.length; j--) {

                    arr[j-1] = arr[j];

                }

                arr[arr.length - 1] = temp;

                continue;

            }

            win = 1;

            int temp = arr[0];

            for (int j = 1; j < arr.length; j--) {

                arr[j-1] = arr[j];

            }

            arr[arr.length - 1] = temp;

        }

        return arr[0];

    }

}


Arr: 2,8,5,6,6 k=3

8,5,6,6,2

8,6,6,2,5

8,6,2,5,6

8


No comments:

Post a Comment