Ball picking game: take one or two from the front
I was asked this
No reports yet. Sign in to say where you were asked it.
Balls stand in a single line. Each ball has an integer value, which may be positive, zero, or negative. Two players take turns, and player 1 moves first. Both start with a score of 0.
On each turn, the player to move must take either one or two balls from the front of the line and adds their values to their score. A player cannot pass, so when one ball is left the player to move must take it, even if its value is negative. The game ends when the line is empty.
Both players play optimally, and each wants to maximize their own final score.
Implement:
def final_scores(balls: list[int]) -> tuple[int, int]:
"""Return (player 1 score, player 2 score) under optimal play."""
def first_player_wins(balls: list[int]) -> bool:
"""Return True if player 1 ends with at least as many points as player 2."""
Constraints
0 <= len(balls) <= 10^5-10^4 <= balls[i] <= 10^4
Example 1
balls = [2, -1, 6]
final_scores(balls) -> (2, 5)
first_player_wins(balls) -> False
If player 1 takes 2, player 2 takes -1, 6 for 5. If player 1 takes 2, -1 (1 point), player 2 takes 6. Player 1 picks the first line, and still loses 2 to 5.
Example 2
balls = [4, -9, 1, 3]
final_scores(balls) -> (7, -8)
Player 1 takes 4. Player 2 must now start with -9, and takes -9, 1. Player 1 takes 3.
Be ready to explain how your answer changes if a player may take up to k balls per turn, or may take from either end of the line.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
