Leetcode 1140: Stone Game II

grid47
grid47
Exploring patterns and algorithms
Jul 16, 2024 7 min read

Alice and Bob are playing a game with piles of stones. Each pile contains a positive integer number of stones. On each player’s turn, they can take stones from the first X remaining piles, where 1 <= X <= 2M. The goal is to maximize the number of stones Alice can collect assuming both play optimally.
Problem
Approach
Steps
Complexity
Input: You are given a list `piles`, where each element `piles[i]` represents the number of stones in the ith pile.
Example: Input: piles = [3, 5, 8, 7, 6]
Constraints:
• 1 <= piles.length <= 100
• 1 <= piles[i] <= 10^4
Output: Return the maximum number of stones Alice can collect if both players play optimally.
Example: Output: 14
Constraints:
• The result will be an integer representing the maximum number of stones Alice can collect.
Goal: Find the optimal strategy for Alice to collect the maximum number of stones, while simulating the game with Bob's optimal strategy.
Steps:
• 1. Calculate the cumulative sum of the piles in reverse order (postfix sum).
• 2. Use dynamic programming (DP) to store the optimal results for different states (index and M).
• 3. Recursively calculate the maximum number of stones Alice can collect given the current state and optimal plays of both players.
Goal: The problem must handle the maximum constraints efficiently.
Steps:
• 1 <= piles.length <= 100
• 1 <= piles[i] <= 10^4
Assumptions:
• The players take turns and Alice always plays first.
• Both players play optimally, i.e., they maximize their score while minimizing the opponent's score.
Input: Input: piles = [3, 5, 8, 7, 6]
Explanation: In this example, Alice starts by taking 1 pile. Then Bob takes 2 piles, Alice takes 2 more piles, and Bob takes the remaining piles. Alice's total is 3 + 7 + 6 = 14.

Input: Input: piles = [1, 2, 3, 4, 6, 80]
Explanation: In this example, Alice can maximize her score by taking the first pile, Bob takes 2 piles, Alice then takes 2 piles, and Bob takes the remaining stones. Alice collects 1 + 4 + 6 + 80 = 84.

Link to LeetCode Lab


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