Removal Game

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 nvector<int&a)
{

    long long sum = 0;

    //sum of array elements
    for (int i = 0i < ni++)
        sum += a[i];
    long long dp[n][n];

    //fill dp with all zeros
    memset(dp0, sizeof dp);
    for (int i = n - 1i >= 0i--)
    {
        for (int j = ij < nj++)
        {
            if (i == j)
                dp[i][j] = a[i];
            else
                dp[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<inta = {4513};

    cout << removalGame(na<< "\n";

    return 0;
}


No comments:

Post a Comment