Optimal Strategy For A Game

You are given an array A of size N. The array contains integers and is of even length. The elements of the array represent N coin 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 value of the coin.

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


example:

input:

arr[4]={5 3 7 10}


output:

The user collects maximum value as 15(10 + 5)



lets use dynamic programming to solve this question:

t is no.  of test cases:

#include<iostream>
using namespace std;
int main(){
	int t;
	cin>>t;
	while(t--){
	    int n;
	    cin>>n;
	    int arr[n];
	    for(int i=0;i<n;i++)
	        cin>>arr[i];
	    int dp[n][n];
	    for(int i=0;i<n-1;i++)
	        dp[i][i+1] = max(arr[i],arr[i+1]);
	    for(int gap=3;gap<n;gap+=2){
	        for(int i=0;i+gap<n;i++){
	            int j = i+gap;
	            dp[i][j] = max(arr[i]+min(dp[i+2][j],dp[i+1][j-1]),arr[j]+min(dp[i+1][j-1],dp[i][j-2]));
	        }
	    }
	    cout<<dp[0][n-1]<<endl;
	}
	return 0;
}


if you want to have a clear understanding watch this video  https://youtu.be/WRXCwgdni90


No comments

darkmode