Determine the Winner of a Bowling Game - Complete Solution Guide
Determine the Winner of a Bowling Game is LeetCode problem 2660, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given two 0-indexed integer arrays player1 and player2 , representing the number of pins that player 1 and player 2 hit in a bowling game, respectively. The bowling game consists of n turns, and the number of pins in each turn is exactly 10. Assume a player hits x i pins in the i th turn. The value of the i th turn for the player is: 2x i if the player hits 10 pins in either (i - 1) th or (i - 2) th turn . Otherwise, it is x i . The score of the player is the sum of the values of their n
Detailed Explanation
The problem simulates a simplified bowling game between two players. Each player's performance is represented by an array where each element indicates the number of pins knocked down in a turn. The scoring system is unique: if a player knocks down 10 pins in either the previous or the turn before the previous, their score for the current turn is doubled. The goal is to determine the winner (player 1, player 2, or a draw) based on their total scores.
Solution Approach
The solution uses a straightforward iterative approach. For each player, it iterates through their score array. It checks if the previous one or two turns resulted in a score of 10. If so, the current turn's score is doubled before being added to the running total. Finally, it compares the total scores of both players to determine the winner.
Step-by-Step Algorithm
- Step 1: Initialize the scores for player 1 and player 2 to 0.
- Step 2: Iterate through the `player1` array. For each element (score), check if the previous two scores (if they exist) are equal to 10. If either is 10, double the current score. Add the (possibly doubled) score to `score1`.
- Step 3: Repeat Step 2 for `player2`, calculating `score2`.
- Step 4: Compare `score1` and `score2`. Return 1 if `score1 > score2`, 2 if `score2 > score1`, and 0 if they are equal.
Key Insights
- Insight 1: The scoring system requires iterating through the player's scores, considering the previous two turns to determine score multipliers.
- Insight 2: A simple iterative approach is sufficient to calculate the total score for each player. No complex data structures are needed.
- Insight 3: Edge cases must be handled, specifically the first two turns where there are no previous turns to check for a bonus.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Simulation.
Companies
Asked at: DE Shaw.