Optimal Matrix Game - Problem

Two players are playing an optimal strategy game with a row of numbers. Players take turns picking numbers from either end of the row. Each player tries to maximize their own score.

Given an array nums representing the row of numbers, return the maximum score that the first player can obtain, assuming both players play optimally.

Note: The first player always goes first. Both players have perfect information and play to maximize their own score.

Input & Output

Example 1 — Basic Game
$ Input: nums = [1,5,2]
Output: 6
💡 Note: First player picks 2, second player picks 5, first player picks 1. First player gets 2 + 1 = 3, but optimal play gives first player 6 total by picking 1 first, forcing second player to pick optimally from [5,2].
Example 2 — Larger Array
$ Input: nums = [1,5,233,7]
Output: 240
💡 Note: First player can pick 7, then after second player's optimal move, pick 233. Total: 233 + 7 = 240.
Example 3 — Equal Elements
$ Input: nums = [3,3,3,3]
Output: 6
💡 Note: Players alternate picking 3s. First player gets first and third picks: 3 + 3 = 6.

Constraints

  • 1 ≤ nums.length ≤ 20
  • 0 ≤ nums[i] ≤ 107

Visualization

Tap to expand
INPUTALGORITHMRESULT152Array: [1, 5, 2]Two players take turnspicking from either endPlayer 1 goes firstBoth play optimallyGoal: maximize own score1Base Casesdp[i][i] = nums[i]2Build TableFill for length 2, 3, ...3Optimal ChoicePick left or right end4Calculate ScoreUse advantage formula2D DP Tabledp[i][j] = max advantageon subarray [i...j]6Maximum Scorefor Player 1Optimal strategy:• Pick from positionthat maximizesremaining advantageTime: O(n²)Space: O(n²)Key Insight:Each subgame has optimal play - solve small segments first,then combine to find the overall optimal strategy for both players.TutorialsPoint - Optimal Matrix Game | 2D Dynamic Programming
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen