#1535

Find the Winner of an Array Game

specialist · 765 · lc medium +31 · verified · 56.8% accepted · 1,623 likes · top 52%

Description

Given a distinct-integer array arr and a positive integer k, a game repeatedly pits arr[0] against arr[1]: the larger stays at position 0 while the smaller is appended to the end. The first element that wins k consecutive comparisons is the overall winner. Return that element (a winner is guaranteed to exist).

Example 1:

Input: arr = [2,1,3,5,4,6,7], k = 2
Output: 5
Explanation: Let's see the rounds of the game:
Round | arr | winner | win_count
1 | [2,1,3,5,4,6,7] | 2 | 1
2 | [2,3,5,4,6,7,1] | 3 | 1
3 | [3,5,4,6,7,1,2] | 5 | 1
4 | [5,4,6,7,1,2,3] | 5 | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.

Example 2:

Input: arr = [3,2,1], k = 10
Output: 3
Explanation: 3 will win the first 10 rounds consecutively.

Code

1
2
3