# Stone Game II in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose there are two persons Alice and Bob, they are continuing their games with piles of stones. There are a number of piles placed in a row, and each pile has a positive integer number of stones in an array piles[i]. Our objective of the game is to end with the most stones. Alice and Bob take the turns, with Alice starting first. Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, here 1 <= X <= 2M. Then, we set M = max(M, X). The game ends when no stones are left. So if piles = [2,7,9,4,4], then the output will be 10. This is because if Alice takes one pile at the beginning, then Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 total piles in her hand. If Alice takes two piles at the beginning, then Bob can take all three piles that are left. In this case, Alice get 2 + 7 = 9 piles. So we will get return 10 since it's larger.

To solve this, we will follow these steps −

• Create one recursive function called solve, that will take array, i, m and one matrix called dp.
• if i >= size of arr, then return 0
• if dp[i, m] is not -1, then return dp[i, m]
• if i – 1 + 2m >= size of array, then return arr[i]
• op := inf
• for x in range 1 to 2m
• op := min of op, solve(arr, i + x, max of x and m, dp)
• dp[i, m] := arr[i] – op
• return dp[i, m]
• the actual method will be like −
• n := size of piles array, make one array called arr of size n
• arr[n - 1] := piles[n – 1]
• for i := n – 2 down to 0
• arr[i] := arr[i + 1] + piles[i]
• create one matrix of size (n + 1) x (n + 1) and fill this with -1
• return solve(arr, 0, 1, dp)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void printVector(vector <int> v){
for(int i =0;i<v.size();i++)cout << v[i] << " ";
cout << endl;
}
int stoneGameII(vector<int>& piles) {
int n = piles.size();
vector <int> arr(n);
arr[n-1] = piles[n-1];
for(int i = n-2;i>=0;i--)arr[i] = arr[i+1] + piles[i];
vector < vector <int> > dp(n+1,vector <int> (n+1,-1));
return solve(arr,0,1,dp);
}
int solve(vector <int> arr, int i, int m, vector < vector <int> > &dp){
if(i >=arr.size())return 0;
if(dp[i][m]!=-1)return dp[i][m];
if(i-1+2*m >=arr.size())return arr[i];
int opponentCanTake = INT_MAX;
for(int x =1;x<=2*m;x++){
opponentCanTake = min(opponentCanTake,solve(arr,i+x,max(x,m),dp));
}
dp[i][m] = arr[i] - opponentCanTake;
return dp[i][m];
}
};
main(){
vector<int> v = {2,7,9,4,4};
Solution ob;
cout <<(ob.stoneGameII(v));
}

## Input

[2,7,9,4,4]

## Output

10
Updated on 30-Apr-2020 12:44:15