Leetcode 2029: Stone Game IX

grid47
grid47
Exploring patterns and algorithms
Apr 18, 2024 5 min read

Alice and Bob are playing a game with stones. The sequence of n stones has values given in an array stones. Players take turns to remove a stone. The player who removes a stone, making the sum of all removed stones divisible by 3, loses. If all stones are removed, Bob wins automatically. Determine if Alice wins or Bob wins, assuming both play optimally.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `stones` representing the values of the stones. Alice and Bob alternate turns, starting with Alice. On each turn, one stone is removed.
Example: stones = [3, 2]
Constraints:
• 1 <= stones.length <= 10^5
• 1 <= stones[i] <= 10^4
Output: Return `true` if Alice wins and `false` if Bob wins.
Example:
Constraints:
Goal: The goal is to determine the winner of the game based on the values of the stones and the optimal moves by both players.
Steps:
• 1. Count the number of stones with values that leave remainders of 0, 1, and 2 when divided by 3.
• 2. Use the counts of stones with each remainder to decide the optimal moves for Alice and Bob.
• 3. Check if the sum of the removed stones after each turn is divisible by 3 to determine the winner.
Goal: Constraints for the number of stones and their values.
Steps:
• 1 <= stones.length <= 10^5
• 1 <= stones[i] <= 10^4
Assumptions:
• Players will always play optimally and aim to avoid the sum of removed stones being divisible by 3.
Input: stones = [3, 2]
Explanation: Alice removes the stone with value 2, and Bob removes the stone with value 3. The sum of the removed stones is 5, which is not divisible by 3, so Alice wins.

Input: stones = [1, 1, 1]
Explanation: Alice removes one stone (value 1), Bob removes another (value 1), and Alice removes the last one (value 1). The sum is 3, divisible by 3, so Alice loses and Bob wins.

Input: stones = [4, 6, 2]
Explanation: Alice removes the stone with value 2, Bob removes the stone with value 4, and Alice removes the last stone with value 6. The sum is 12, divisible by 3, so Alice wins.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus