There is a list of n numbers and two players who move alternately. On each move, a player removes either the first or last number from the list and their score increases by that number. Both players try to maximize their scores.
What is the maximum possible score for the first player when both players play optimally?
Example:
Input: n = 4, a = {4, 5, 1, 3}
Output: 8
Approach
C++
#include <bits/stdc++.h>using namespace std;long long removalGame(int n, vector<int> &a){long long sum = 0;//sum of array elementsfor (int i = 0; i < n; i++)sum += a[i];long long dp[n][n];//fill dp with all zerosmemset(dp, 0, sizeof dp);for (int i = n - 1; i >= 0; i--){for (int j = i; j < n; j++){if (i == j)dp[i][j] = a[i];elsedp[i][j] = max(a[i] - dp[i + 1][j], a[j] - dp[i][j - 1]);}}return (sum + dp[0][n - 1]) / 2;}int main(){int n = 4;vector<int> a = {4, 5, 1, 3};cout << removalGame(n, a) << "\n";return 0;}
No comments:
Post a Comment