Optimal Game Strategy-1

#include
using namespace std;
int game(int*arr,int i,int n)
{
if(n<i)
{
return 0;
}
int y=0;
if(arr[i]>arr[n])
{
if(arr[i+1]>arr[n-1])
{
y=arr[i]+game(arr,i+2,n);
}
else
{
y=arr[i]+game(arr,i+1,n-1);
}
}
else
{
y+=arr[n];
if(arr[i]>arr[n-1])
{
y+=game(arr,i+1,n-1);
}
else{
y+=game(arr,i,n-2);}
}
return y;
}
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<game(arr,0,n-1);
return 0;
}
what wrong in this code?

hello @Pranav7g you have implemented the question in the wrong way as you can see in the question that both the players play optimally that means both the players will try to win .
that is the reason you have to minimise the nimits case as piyush starts first.
you have to minimise the nimit choice and you hvae to choose the maximum of both for the piyush.
this is how you have to implement the code for this question .
i hope i have explained you in the right way .
if you still have any doubt please ask here .
Happy Learning !!

#include using namespace std; int game(int*arr,int i,int n) { if(n<i) { return 0; } int y=0; if(arr[i]>arr[n]) { if(arr[i+1]>arr[n-1]) { y=arr[i]+game(arr,i+1,n-1); } else { y=arr[i]+game(arr,i+2,n); } } else { y+=arr[n]; if(arr[i]>arr[n-1]) { y+=game(arr,i,n-2); } else{ y+=game(arr,i+1,n-1); } } return y; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } cout<<game(arr,0,n-1); return 0; }

is this code is correct?

if piyush want to maximise his score then why the ans of this test case(1,2,3,4) is 6 it should be 7 becoz piyush pick 4th coin then nimit put 1st coin then piyus have to put 3rd coin so at last max score is 7 so why the ans is 6

question give explination “Piyush will pick the coin 4. Then Nimit can pick either 1 or 3. In both the cases piyush picks coin 2 and wins with a total of 6.”

@Pranav7g your code is unreaddable please share it by saving on ide.codingblocks.com

@Pranav7g we dont have to minimise the value for nimit for that particular value but we have to minimise the overall result.
like in the sample test case when piyush picks up the max element i.e 4 then you nimit will pick up 3 as he is also playing optimally .
by optimally we mean that every turn of nimit will try to maximise his result.
let us take the example of the test case .
10
22 50 16 13 8 41 25 43 8 7
in this the piyush chooses number are 7+50+13+41+43
and nimit chooses number are 22+16+8+25+8.
and the output for piyush will be 154.
i hope i have cleared your doubt .
Happy Learning !!

1 Like

hey @Pranav7g as you are not replying to the post i am marking this doubt as resolved .
on off the chance if you still have doubt in this you can reopen this .
Happy Learning !!

1 Like