Question explanation

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. But i want to ask if nimit picks coin 1 so the remaining coins will be 2 ,3 so piyush can pick coin 3 and have a total of 7 . Are we removing both the coins that nimit can choose from the array ?

I have build a program according to the logic of removing both :

#include
using namespace std;

int optimal(int *a, int n, int s, int e, int piyushTurn, int maxPiyush)
{
if (s > e)
{
return maxPiyush;
}
// piyush turn
if (piyushTurn % 2 == 1)
{
if (a[s] <= a[e])
{
maxPiyush += a[e];
return optimal(a, n, s , e - 1, piyushTurn + 1, maxPiyush);
}
else
{
maxPiyush += a[s];
return optimal(a, n, s + 1, e, piyushTurn + 1, maxPiyush);
}
}
// Nimit turn
else
{
return optimal(a, n, s + 1, e - 1, piyushTurn + 1, maxPiyush);
}
}

int main()
{
int n;
cin >> n;
int a[30];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
cout << optimal(a, n, 0, n - 1, 1, 0);

return 0;

}

Please tell me where i am wrong

refer this https://ide.codingblocks.com/s/321691

i am asking the correct explanation of the question and where i am wrong .please tell me that

please save ur code on ide and send. and can u explain what exactly are u trying to do in code?

the main logic is Piyush in every turn would try to make max element from starting or ending of array and then in next turn if Nimit takes min element from starting or ending of array only then would we be able to maximize score of Piyush

In this program i am tracking piyush turn by checking odd/even if odd it is piyush turn then i find the max of start and end and add it to maxvalue then next is nimish turn and i skip the min of the first and last value

4
1 2 3 4

in this sample input piyush will pick 4 then nimit will pick 1 then 2, 3 will be left and piyush will pick 3 causing the max value to be 7 and not 6 as it it explained with the sample input.

There’s slight error in wording of explanation of output. In question it is given that both the players play optimally. therefore Nimit will also try to pick max value

Ohh ok

Optimized the code according to this logic, only one test case passed though the code seems simple enough to work. Can you please take a look

even if u optimize the code it will fail test cases. this question is basically of dynamic programming and is given in recursion section just to give insight.
so try with https://ide.codingblocks.com/s/321691 or move ahead

ooh ok !! thank you very much.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.