algoadvance

Leetcode 2660. Determine the Winner of a Bowling Game

Problem Statement

Given the scores of two players in a bowling game, determine the winner. The format of the input and specific rules such as the number of frames, scoring for strikes and spares, or any other special rules are not specified in this statement. Thus, for simplicity, we will consider the most basic scenario where each player has a list of scores for each frame (no strikes or spares). The player with the higher total score wins.

Clarifying Questions

  1. How many players are there?
    • There are two players.
  2. What does the input look like?
    • The input consists of two vectors of integers, where each vector contains the scores for each frame of the respective player.
  3. Are there any constraints on the length of the input vectors?
    • Yes, both vectors will have the same length and will represent the number of frames bowled. This length will be fixed for both players.
  4. How do strikes and spares affect scores?
    • We’ll assume there are no strikes or spares for simplicity.
  5. What should be returned or printed?
    • The function should return the index of the winning player (0 or 1) or -1 in case of a tie.

Strategy

  1. Sum the scores of each player’s frames.
  2. Compare the total scores.
  3. Return the index of the player with the higher score. In case of a tie, return -1.

Code

#include <vector>
#include <numeric>
#include <iostream>

int determineWinner(const std::vector<int>& player1_scores, const std::vector<int>& player2_scores) {
    // Calculate the total score for player 1
    int player1_total = std::accumulate(player1_scores.begin(), player1_scores.end(), 0);
    
    // Calculate the total score for player 2
    int player2_total = std::accumulate(player2_scores.begin(), player2_scores.end(), 0);
    
    // Determine the winner
    if (player1_total > player2_total) {
        return 0;  // Player 1 is the winner
    } else if (player2_total > player1_total) {
        return 1;  // Player 2 is the winner
    } else {
        return -1; // It's a tie
    }
}

int main() {
    std::vector<int> player1_scores = {10, 9, 5, 6}; // Example input
    std::vector<int> player2_scores = {7, 8, 10, 6}; // Example input
    
    int result = determineWinner(player1_scores, player2_scores);
    
    if (result == -1) {
        std::cout << "It's a tie.\n";
    } else {
        std::cout << "The winner is player " << result << ".\n";
    }
    
    return 0;
}

Time Complexity

This solution is efficient given the constraints and directly addresses the problem of determining the winner based on total scores in a straightforward manner.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI