Skip to content

1535. Find the Winner of an Array Game 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int getWinner(vector<int>& arr, int k) {
    int ans = arr[0];
    int wins = 0;

    for (int i = 1; i < arr.size() && wins < k; ++i)
      if (arr[i] > ans) {
        ans = arr[i];
        wins = 1;
      } else {
        ++wins;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int getWinner(int[] arr, int k) {
    int ans = arr[0];
    int wins = 0;

    for (int i = 1; i < arr.length && wins < k; ++i)
      if (arr[i] > ans) {
        ans = arr[i];
        wins = 1;
      } else {
        ++wins;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def getWinner(self, arr: list[int], k: int) -> int:
    ans = arr[0]
    wins = 0

    i = 1
    while i < len(arr) and wins < k:
      if arr[i] > ans:
        ans = arr[i]
        wins = 1
      else:
        wins += 1
      i += 1

    return ans