![]() |
VOOZH | about |
It is strongly recommended to first refer Optimal Strategy for a Game problem as a prerequisite. Let us now talk about a variation problem. Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player performs the following operation K times.
The player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin.
Determine the maximum possible amount of money the user can definitely win if the user moves first.
Note: The opponent is as clever as the user.
Examples:
Input : array = {10, 15, 20, 9, 2, 5}, k=2
Output :32
Explanation:
Lets say, user has initially picked 10 and 15.
The value of coins which the user has is 25 and
{20, 9, 2, 5} are remaining in the array.
In the second round, the opponent picks 20 and 9 making his value 29.
In the third round, the user picks 2 and 5 which makes his total value as 32.
Input: array = {10, 15, 20, 9, 2}, k=1
Output: 32
Approach:
A recursive solution needs to be formed and the values of sub problems needs to be stored to compute the result.
Taking an example to arrive at the recursive solution;
arr = {10, 15, 20, 9, 2, 5}, k=2
So if the user selects 10, 15 in the first turn then 20, 9, 2, 5 are left in the array.
But if the user selects 10, 5; then 15, 20, 9, 2 are left in the array.
Lastly, if the user selects 5, 2; then 10, 15, 20, 9 are left in the array.
So at any iteration after selecting k elements, a continuous subarray of length n-k is remaining for next computation.
So recursive solution can be formed where :
S(l, r) = (sum(l, r) - sum(l+i, l+i+n-k-1))+(sum(l+i, l+i+n-k-1) - S(l+i, l+i+n-k-1))
where l+i+n-k-1<=r
Sum of chosen elements Sc=(sum(l, r) - sum(l+i, l+i+n-k-1))
Now the opponent will perform the next turn so
Sum of Elements chosen in next steps = Total sum of present array from l to r -
Sum of elements chosen by opponent in next steps which is equal to
Nc=(sum(l+i, l+i+n-k-1) - S(l+i, l+i+n-k-1)).
S(l, r) = Sc + Nc
where,
Nc=(sum(l+i, l+i+n-k-1) - S(l+i, l+i+n-k-1))
Sc=(sum(l, r) - sum(l+i, l+i+n-k-1))
Below is the implementation of the above approach:
32
Time Complexity: O(r2)
Auxiliary Space: O(101 * 101 * 101)