Determine the Winner of a Bowling Game

This problem requires us to compare the scores of two players in a bowling game. Each player has the same number of turns and the number of pins hit by each player in each turn is known. The score for a turn is twice the number of pins hit in that turn if the player hit all 10 pins in any of the previous two turns, otherwise, it is the number of pins hit in that turn. The total score is the sum of the scores for all turns.

We can solve this problem by first computing the total scores for both players and then comparing the scores to determine the winner.

Here is the Python code:

 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
26
27
class Solution:
    def isWinner(self, player1: List[int], player2: List[int]) -> int:
        n = len(player1)
        scores1, scores2 = [0]*n, [0]*n  # initialize scores

        # compute scores for player1
        for i in range(n):
            if i > 0 and (player1[i-1] == 10 or (i > 1 and player1[i-2] == 10)):
                scores1[i] = player1[i] * 2 
            else:
                scores1[i] = player1[i]

        # compute scores for player2
        for i in range(n):
            if i > 0 and (player2[i-1] == 10 or (i > 1 and player2[i-2] == 10)):
                scores2[i] = player2[i] * 2
            else:
                scores2[i] = player2[i]

        # compare total scores
        total_score1, total_score2 = sum(scores1), sum(scores2)
        if total_score1 > total_score2:
            return 1
        elif total_score1 < total_score2:
            return 2
        else:
            return 0

This code first initializes two lists, scores1 and scores2, to store the scores for each turn for both players. Then it computes the scores for all turns for both players according to the rules of the game. Finally, it computes the total scores for both players and compares them to determine the winner. If player1’s total score is higher, it returns 1, if player2’s total score is higher, it returns 2, if both total scores are equal, it returns 0.