Skip to content

2660. Determine the Winner of a Bowling Game

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int isWinner(vector<int>& player1, vector<int>& player2) {
    const int score1 = getScore(player1);
    const int score2 = getScore(player2);
    if (score1 > score2)
      return 1;
    if (score2 > score1)
      return 2;
    return 0;
  }

 private:
  int getScore(const vector<int>& player) {
    constexpr int kInvalid = -3;
    int score = 0;
    int last10 = kInvalid;
    for (int i = 0; i < player.size(); ++i) {
      score += i - last10 > 2 ? player[i] : player[i] * 2;
      if (player[i] == 10)
        last10 = i;
    }
    return score;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int isWinner(int[] player1, int[] player2) {
    final int score1 = getScore(player1);
    final int score2 = getScore(player2);
    if (score1 > score2)
      return 1;
    if (score2 > score1)
      return 2;
    return 0;
  }

  private int getScore(int[] player) {
    final int kInvalid = -3;
    int score = 0;
    int last10 = kInvalid;
    for (int i = 0; i < player.length; ++i) {
      score += i - last10 > 2 ? player[i] : player[i] * 2;
      if (player[i] == 10)
        last10 = i;
    }
    return score;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def isWinner(self, player1: list[int], player2: list[int]) -> int:
    def getScore(player: list[int]) -> int:
      kInvalid = -3
      score = 0
      last10 = kInvalid
      for i, p in enumerate(player):
        score += p if i - last10 > 2 else p * 2
        if p == 10:
          last10 = i
      return score

    score1 = getScore(player1)
    score2 = getScore(player2)
    if score1 > score2:
      return 1
    if score2 > score1:
      return 2
    return 0