2660. Determine the Winner of a Bowling Game

ArraySimulation

Explanation

To solve this problem, we need to calculate the scores of both players based on the given rules and compare them to determine the winner. We can iterate through each turn for both players, calculate the score for each turn according to the rules provided, and then sum up the scores to get the total score for each player. Finally, we compare the total scores to determine the winner.

Algorithm:

  1. Initialize variables to store the total scores of player 1 and player 2.
  2. Iterate through each turn for both players.
  3. For each turn, calculate the score based on the rules provided.
  4. Sum up the scores for each player to get the total score.
  5. Compare the total scores to determine the winner.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of turns in the game.

Space Complexity:

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space regardless of the input size.

class Solution {
    public int determineWinner(int[] player1, int[] player2) {
        int scorePlayer1 = 0, scorePlayer2 = 0;
        
        for (int i = 0; i < player1.length; i++) {
            int turnScore1 = calculateTurnScore(player1, i);
            int turnScore2 = calculateTurnScore(player2, i);
            
            scorePlayer1 += turnScore1;
            scorePlayer2 += turnScore2;
        }
        
        if (scorePlayer1 > scorePlayer2) {
            return 1;
        } else if (scorePlayer2 > scorePlayer1) {
            return 2;
        } else {
            return 0;
        }
    }
    
    private int calculateTurnScore(int[] player, int index) {
        if (index >= 2 && player[index] == 10 && (player[index - 1] == 10 || player[index - 2] == 10)) {
            return 2 * player[index];
        } else {
            return player[index];
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.