Welcome back to my 100-day Data Structures and Algorithms (DSA) challenge! On day 14, I encountered a fascinating problem on LeetCode called "Predict the Winner." As I delved into the solution, I stumbled upon a concept I hadn't explored before—the Minimax optimal game strategy algorithm.
The Problem: Predict the Winner
The problem statement involves an array of numbers representing points. Two players take turns picking numbers from either end of the array until there are no more elements left. The goal is to predict whether the first player can win, assuming both players play optimally.
The Initial Approach
To solve this problem, I implemented a recursive approach with memoization. I created a C++ solution using a class with a private helper function solution
and a public function predictTheWinner
.
class Solution {
public:
int t[25][25];
int solution(vector<int> nums, int i, int j) {
// Base case
if (i > j) {
return 0;
}
if (i == j) {
return nums[i];
}
if (t[i][j] != -1) {
return t[i][j];
}
int choose_i = nums[i] - solution(nums, i + 1, j);
int choose_j = nums[j] - solution(nums, i, j - 1);
return t[i][j] = max(choose_i, choose_j);
}
bool predictTheWinner(vector<int>& nums) {
int n = nums.size();
memset(t, -1, sizeof(t));
return (solution(nums, 0, n - 1)) >= 0;
}
};
This code defines a class with a memoization table t
to store already computed subproblems, ensuring an optimized solution.
The Fascinating Concept: Minimax Algorithm
As I explored this problem, I stumbled upon the Minimax algorithm—a decision-making strategy for minimizing the possible loss for a worst-case scenario. In the context of game theory, it's used to determine the optimal move for a player, assuming that the opponent will also make optimal moves.
In our scenario, the algorithm evaluates all possible moves, assigning scores to each, and chooses the one with the highest score for the current player.
Reflecting on the Implementation
The predictTheWinner
function returns true
if the first player can win and false
otherwise. It utilizes the solution
function, which recursively calculates the maximum score the first player can achieve.
The core idea is to subtract the score of the second player's optimal move from the score of the first player's move. If the resulting score is non-negative, the first player is predicted to win.
Conclusion
Day 14 brought not only a coding challenge but also an exciting exploration into the Minimax algorithm. The recursive approach with memoization served as an effective tool to predict the winner in a game scenario. As I continue this DSA journey, I look forward to encountering more intriguing concepts and solving challenging problems.
Stay tuned for the next day of the 100-day DSA challenge! Happy coding!