
Sponsored
Sponsored
This approach involves simulating the game as described. In each round, compare the first two elements. The larger element stays at the front, while the smaller one is moved to the end. Track the number of consecutive wins for the current maximum element. The game terminates once an element wins k consecutive games, or we can conclude the maximum element will always win once it has dominated for enough rounds due to its magnitude relative to other elements.
Time Complexity: O(n) where n is the length of the array.
Space Complexity: O(1) as we use only constant space.
1class Solution {
2 public int getWinner(int[] arr, int k) {
3 int max = arr[0];
4 int winCount = 0;
5 for (int i = 1; i < arr.length; ++i) {
6 if (max > arr[i]) {
7 winCount++;
8 } else {
9 max = arr[i];
10 winCount = 1;
11 }
12 if (winCount == k) return max;
13 }
14 return max;
15 }
16
17 public static void main(String[] args) {
18 Solution sol = new Solution();
19 int[] arr = {2, 1, 3, 5, 4, 6, 7};
20 int k = 2;
21 System.out.println("Winner: " + sol.getWinner(arr, k));
22 }
23}This Java implementation iterates over the array, keeping track of the current maximum and counting how many times it wins consecutively. The function stops and returns this maximum once a number wins k times, or after evaluating all elements in case the maximum changes before k wins.
This variant uses a concept very similar to the simulation approach but adds a breaking condition for improved efficiency. It exploits the game's characteristics by noting if the current maximum wins continuously even before counting to k, it will naturally reach the conclusion. This allows early termination if the maximum element becomes apparent quickly.
Time Complexity: O(n), potentially terminating faster.
Space Complexity: O(1).
1
This C language solution enhances the standard simulation method with a conditional break. It re-evaluates upon encountering the largest possible number, indicated by iterating long enough to guarantee the outcome irrespective of k, hence optimizing rounds required for final decision.