Optimal Game Strategy (Array Ends)
Reported
3 times
Last seen
2021-11-29
First seen
2021-11-29
Active in
2021, 2024, 2025
Description
Two players take turns picking a number from either the **left end** or the **right end** of an array. Both play optimally (maximizing their own total). Determine the maximum score the first player can guarantee. **Example 1:** ``` arr = [5, 3, 7, 10] Player 1 picks 10 (right) → [5, 3, 7] Player 2 picks 7 (right) → [5, 3] Player 1 picks 5 (left) → [3] Player 2 picks 3 Player 1 score: 10 + 5 = 15 Player 2 score: 7 + 3 = 10 Player 1 wins with score 15. ``` **Example 2:** ``` arr = [8, 15, 3, 7] Optimal play → Player 1 gets 22, Player 2 gets 11 ``` **Constraints:** - 1 ≤ n ≤ 1000 - 1 ≤ arr[i] ≤ 10^6 - n can be odd or even
Approach Tips
**Key Insight:** This is an interval DP problem. The trick is thinking in terms of "score difference" rather than tracking both players separately. **State Definition:** `dp[i][j]` = maximum score difference the **current player** can achieve from subarray `arr[i..j]` **Recurrence:** ``` dp[i][j] = max( arr[i] - dp[i+1][j], // pick left: gain arr[i], opponent gets dp[i+1][j] arr[j] - dp[i][j-1] // pick right: gain arr[j], opponent gets dp[i][j-1] ) ``` The subtraction is the key insight — after you pick, the opponent becomes the "current player" and their best result *subtracts* from yours. **Base case:** `dp[i][i] = arr[i]` (only one element, current player takes it) **Answer:** `dp[0][n-1] >= 0` means Player 1 can win or tie. ```python def optimal_score(arr): n = len(arr) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = arr[i] for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 dp[i][j] = max( arr[i] - dp[i+1][j], arr[j] - dp[i][j-1] ) return dp[0][n-1] # positive = P1 wins ``` **Complexity:** O(n²) time, O(n²) space. Can be optimized to O(n) space since we only need the previous diagonal. **What interviewers look for:** - Can you identify this as interval DP? (Many try greedy first — greedy fails) - The "score difference" formulation (much cleaner than tracking both players) - Filling the DP table diagonally (by subarray length) - Can you explain *why* greedy fails? (Always picking the larger end doesn't account for what it opens up for the opponent) **Follow-up questions:** - What if there are 3+ players? - What if you can pick from both ends (take up to K from either side)? - Can you reconstruct the actual moves, not just the score?
Related LeetCode Problem
LC 486 - Predict the Winner
Sources
Rippling
HR Tech/SaaS
Typically appears in: Technical Phone Screen
60 min — LeetCode-style problem in CodePair. Meta-like pace expected.