Given an integer array arr
of distinct integers and an integer k
, a game is played as follows:
k
consecutive wins.k
consecutive wins.Constraints:
arr
contains unique elements.
The first idea that comes to mind is to simulate the game exactly as described: repeatedly compare the first two elements, update the win count, and move the loser to the end. This brute-force approach is straightforward but could be inefficient for large arrays or large k
, as it may involve a lot of unnecessary moves, especially if the largest element is at the end.
However, since the largest element cannot be beaten by any other element, it will eventually accumulate k
consecutive wins if k
is large enough. This insight allows us to optimize: we don't have to simulate all moves if we can keep track of the current winner and their streak.
The challenge is to efficiently track the current winner and their consecutive wins without moving elements unnecessarily.
Let's break down the optimized approach step-by-step:
arr
as the current winner.k
, return them immediately.k
(possible if k
is large), return the array's maximum element (as it cannot be beaten).This approach uses a single pass through the array and avoids unnecessary rotations or full simulation, making it efficient.
Let's consider the input arr = [2,1,3,5,4,6,7]
and k = 2
.
k
.
The function returns 5 as the winner.
The optimized approach is much more efficient, especially for large values of n
and k
.
def getWinner(arr, k):
winner = arr[0]
streak = 0
for i in range(1, len(arr)):
if arr[i] > winner:
winner = arr[i]
streak = 1
else:
streak += 1
if streak == k:
return winner
return winner
int getWinner(vector<int>& arr, int k) {
int winner = arr[0];
int streak = 0;
for (int i = 1; i < arr.size(); ++i) {
if (arr[i] > winner) {
winner = arr[i];
streak = 1;
} else {
++streak;
}
if (streak == k) return winner;
}
return winner;
}
public int getWinner(int[] arr, int k) {
int winner = arr[0];
int streak = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > winner) {
winner = arr[i];
streak = 1;
} else {
streak++;
}
if (streak == k) return winner;
}
return winner;
}
var getWinner = function(arr, k) {
let winner = arr[0];
let streak = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > winner) {
winner = arr[i];
streak = 1;
} else {
streak++;
}
if (streak === k) return winner;
}
return winner;
};
The key insight in this problem is that the largest element will always eventually win if k
is large. By tracking only the current winner and their consecutive wins, we avoid unnecessary array operations and achieve a linear time solution. This approach is both simple and efficient, making use of the problem's constraints and properties for an elegant solution.