-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOptimalGameStrategy.cpp
More file actions
82 lines (76 loc) · 2.1 KB
/
Copy pathOptimalGameStrategy.cpp
File metadata and controls
82 lines (76 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
GFG Problem-
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 amount of money you can win if you go first.
Input:
N = 4
A[] = {5,3,7,10}
Output: 15
Dynamic Programming - Top Down + Tabulation
*/
typedef long long int lli;
struct Node
{
lli p1,p2;
};
void maximumAmt(int arr[], int n,struct Node**Dp,int low,int high,int player)
{
if(Dp[low][high].p1!=-1)
{
return;
}
if(low==high)
{
Dp[low][high].p1=arr[low];
Dp[low][high].p2=0;
return;
}
maximumAmt(arr,n,Dp,low+1,high,1-player);
maximumAmt(arr,n,Dp,low,high-1,1-player);
if(player==0)
{
if(Dp[low+1][high].p1+arr[low]>Dp[low][high-1].p1+arr[high])
{
Dp[low][high].p1=Dp[low+1][high].p1+arr[low];
Dp[low][high].p2=Dp[low+1][high].p2;
}
else
{
Dp[low][high].p1=Dp[low][high-1].p1+arr[high];
Dp[low][high].p2=Dp[low][high-1].p2;
}
}
else
{
if(Dp[low+1][high].p2+arr[low]>Dp[low][high-1].p2+arr[high])
{
Dp[low][high].p2=Dp[low+1][high].p2+arr[low];
Dp[low][high].p1=Dp[low+1][high].p1;
}
else
{
Dp[low][high].p2=Dp[low][high-1].p2+arr[high];
Dp[low][high].p1=Dp[low][high-1].p1;
}
}
return;
}
long long maximumAmount(int arr[], int n)
{
struct Node **Dp=(struct Node **)malloc(n*sizeof(struct Node *));
for(int i=0;i<n;i++)
{
Dp[i]=(struct Node *)malloc(n*sizeof(struct Node));
for(int j=0;j<n;j++)
{
Dp[i][j].p1=Dp[i][j].p2=-1;
}
}
maximumAmt(arr,n,Dp,0,n-1,1);
lli ans=Dp[0][n-1].p2;
for(int i=0;i<n;i++)
free(Dp[i]);
free(Dp);
return ans;
}