06. Optimal Strategy For A Game

βœ… GFG solution to the Optimal Strategy For A Game problem: find maximum amount of money you can win if you go first, assuming both players play optimally. πŸš€

The problem can be found at the following link: πŸ”— Question Link

🧩 Problem Description

You are given an integer array arr[] of size n (even). The array elements represent n coins of values v1, v2, ..., vn. You play against an opponent in an alternating way. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the coin's value.

You need to determine the maximum possible amount of money you can win if you go first.

Note: Both the players are playing optimally.

πŸ“˜ Examples

Example 1

Input: arr[] = [5, 3, 7, 10]
Output: 15
Explanation: The user collects the maximum value as 15(10 + 5). It is guaranteed that we cannot get more than 15 by any possible moves.

Example 2

Input: arr[] = [8, 15, 3, 7]
Output: 22
Explanation: The user collects the maximum value as 22(7 + 15). It is guaranteed that we cannot get more than 22 by any possible moves.

πŸ”’ Constraints

  • $2 \le n \le 10^3$

  • $1 \le arr[i] \le 10^6$

βœ… My Approach

The optimal approach uses Dynamic Programming to efficiently compute the maximum amount the first player can win:

1D DP Optimized Approach

  1. Understanding the Game:

    • Each player can choose either the first or last coin in their turn.

    • Both players play optimally, meaning they will always make the move that maximizes their own total.

    • We need to find the maximum amount the first player can collect.

  2. DP State Definition:

    • Let dp[i][j] represent the maximum advantage the current player can get over the opponent for the subarray arr[i...j].

    • This is the difference between the current player's total and the opponent's total for this subarray.

  3. Recurrence Relation:

    • If the current player picks arr[i], the opponent will then play optimally on the remaining subarray arr[i+1...j]. The current player's advantage would be arr[i] - dp[i+1][j].

    • If the current player picks arr[j], the opponent will then play optimally on the remaining subarray arr[i...j-1]. The current player's advantage would be arr[j] - dp[i][j-1].

    • Therefore, dp[i][j] = max(arr[i] - dp[i+1][j], arr[j] - dp[i][j-1]).

  4. Optimization to 1D:

    • Instead of using a 2D table, we can optimize space by using a 1D array.

    • We process the array from right to left, updating our DP values for each starting index.

  5. Calculating the Result:

    • Let sum be the total sum of all coin values.

    • The maximum amount the first player can collect is (sum + dp[0][n-1]) / 2.

    • This is because dp[0][n-1] represents the difference between the first player's total and the second player's total.

    • If first + second = sum and first - second = dp[0][n-1], then first = (sum + dp[0][n-1]) / 2.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(nΒ²), where n is the size of the array. We need to fill a DP table for all possible subarrays.

  • Expected Auxiliary Space Complexity: O(n), as we only use a single array of size n to store intermediate DP values.

βš™οΈ Code (C)

πŸ§‘β€πŸ’» Code (C++)

⚑ View Alternative Approaches with Code and Analysis

πŸ“Š 2️⃣ 2D DP Table Approach

πŸ’‘ Algorithm Steps:

  1. Create a 2D DP table where dp[i][j] represents max advantage for subarray [i,j].

  2. Fill diagonals first (single elements) then expand to larger subarrays.

  3. At each step, player picks either first or last element optimally.

  4. Calculate final amount by adding half of total sum and advantage.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ²) - Fill all cells in 2D table

  • Auxiliary Space: πŸ’Ύ O(nΒ²) - 2D DP table storage

βœ… Why This Approach?

  • Intuitive visualization of subproblems

  • Clear recursive structure with memoization

  • Easy to trace and debug intermediate states

πŸ“Š 3️⃣ Recursive Memoization

πŸ’‘ Algorithm Steps:

  1. Define recursive function for range [left, right] representing current game state.

  2. Base case when left equals right, return that element value.

  3. Recursively explore picking from left or right end optimally.

  4. Memoize results to avoid recomputing same subproblems.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ²) - Each subproblem computed once

  • Auxiliary Space: πŸ’Ύ O(nΒ²) - Memoization map and recursion stack

βœ… Why This Approach?

  • Top-down approach mirrors natural problem thinking

  • Easier to convert from brute force solution

  • Good for understanding problem structure

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1010/1115 test cases due to time constraints).

πŸ“Š 4️⃣ Space Optimized Rolling Array

πŸ’‘ Algorithm Steps:

  1. Optimize space by maintaining only current and previous row of DP.

  2. Process diagonally from bottom-right to top-left of conceptual table.

  3. Update single array by reusing previously computed values.

  4. Reduce space from O(nΒ²) to O(n) while maintaining correctness.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(nΒ²) - Same computation as 2D approach

  • Auxiliary Space: πŸ’Ύ O(n) - Only two arrays of size n

βœ… Why This Approach?

  • Significant space optimization over 2D DP

  • Maintains optimal time complexity

  • Better cache performance with smaller memory footprint

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 1D DP Optimized

🟒 O(n²)

🟒 O(n)

πŸš€ Best space efficiency

πŸ”§ Less intuitive logic

πŸ“Š 2D DP Table

🟒 O(n²)

🟑 O(n²)

πŸ“– Clear visualization

πŸ’Ύ High memory usage

πŸ”„ Recursive Memo

🟒 O(n²)

🟑 O(n²)

🎯 Natural problem structure

πŸ“š Recursion overhead

⚑ Rolling Array

🟒 O(n²)

🟒 O(n)

⭐ Space optimized

πŸ”§ Moderate implementation complexity

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Production/Memory constrained

πŸ₯‡ 1D DP Optimized

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Understanding

πŸ₯ˆ 2D DP Table

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Prototyping/Quick solution

πŸ₯‰ Recursive Memo

β˜…β˜…β˜…β˜…β˜†

⚑ Balance of clarity & efficiency

πŸ… Rolling Array

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated