Skip to content

Commit 8d4f9a2

Browse files
authored
Create 1535-find-the-winner-of-an-array-game.java
1 parent edcfe07 commit 8d4f9a2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* LeetCode Problem: 1535. Find the Winner of an Array Game
3+
*
4+
* Description:
5+
* Given an integer array arr of distinct integers and an integer k.
6+
* A game will be played between the first two elements of the array (arr[0] and arr[1]).
7+
* In each round, the larger integer wins and remains at the front of the array,
8+
* and the smaller integer moves to the end of the array.
9+
*
10+
* The game ends when an integer wins k consecutive rounds.
11+
* Return the integer that will win the game.
12+
*
13+
* Constraints:
14+
* - 2 <= arr.length <= 10^5
15+
* - 1 <= arr[i] <= 10^6
16+
* - arr contains distinct integers
17+
* - 1 <= k <= 10^9
18+
*/
19+
20+
class Solution {
21+
public int getWinner(int[] arr, int k) {
22+
int ans = arr[0];
23+
int count = 0;
24+
for (int i = 1; i < arr.length; i++) {
25+
if (arr[i] > ans) {
26+
ans = arr[i];
27+
count = 1;
28+
} else {
29+
count++;
30+
}
31+
if (count == k)
32+
return ans;
33+
}
34+
return ans;
35+
}
36+
}

0 commit comments

Comments
 (0)