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 (arr[0] and arr[1]). In each round, the larger integer wins and remains at the front of the array, and the smaller integer moves to the end of the array.
The game ends when an integer wins k consecutive rounds.
Return the integer that will win the game.
2 <= arr.length <= 10^51 <= arr[i] <= 10^6arr contains distinct integers1 <= k <= 10^9Track the current winner and its consecutive win count. Iterate through the array starting from index 1, comparing each element with the current winner. If current element is larger, update winner and reset count to 1. Otherwise, increment the count. If count reaches k, return the current winner.
Why this approach works:
Alternative approaches considered:
Example Input: arr = [2, 1, 3, 5, 4, 6, 7], k = 3
Step-by-step execution:
Final Answer = 7 (Note: In actual game, 7 would continue winning all rounds)
class Solution {
public int getWinner(int[] arr, int k) {
int ans = arr[0];
int count = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > ans) {
ans = arr[i];
count = 1;
} else {
count++;
}
if (count == k)
return ans;
}
return ans;
}
}