Stone Game III in C++

C++Server Side ProgrammingProgramming

Suppose Amal and Bimal are playing with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is a number given in the array called stoneValue.

Amal and Bimal take turns, with Amal starting first. On each player's turn, he/she can take 1, 2 or 3 stones from the first remaining stones in the row.

The score of each player is the sum of values of the stones taken. Initially the score is 0. The goal of the game is to end with the highest score, and the winner is the player with the highest score and there could also be a tie. The game continues until all the stones have been taken.

We will assume that Amal and Bimal are playing optimally. We have to return "Amal" if Amal wins, "Bimal" if Bimal wins or "Tie" if they end the game with the same score.

So, if the input is like values = [1,2,3,7], then the output will be Bimal, As Amal will always lose. His best move will be to take three piles and the score become 6. Now the score of Bimal is 7 and Bimal wins.

To solve this, we will follow these steps −

  • To solve this, we will follow these steps −

  • Define an array dp of size n + 10

  • Define an array sum of size n + 10

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • dp[i] := -(1^9)

  • sum[n - 1] = v[n - 1]

  • for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −

    • sum[i] := sum[i + 1] + v[i]

  • for initialize i := n - 1, when i >= 0, update (decrease i by 1), do −

    • for initialize k := i + 1, when k <= i + 3 and k <= n, update (increase k by 1), do −

      • dp[i] := maximum of dp[i] and sum[i] - dp[k]

  • total := sum[0]

  • x := dp[0]

  • y := total - x

  • return x > y is true, then "Amal" : if x and y are same then "Tie" otherwise "Bimal"

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string stoneGameIII(vector<int>& v) {
      int n = v.size();
      vector <int> dp(n + 10);
      vector <int> sum(n + 10);
      for(int i = 0; i < n; i++)dp[i] = -1e9;
      sum[n - 1] = v[n - 1];
      for(int i = n - 2; i >= 0; i--)sum[i] = sum[i + 1] + v[i];
      for(int i = n- 1 ; i >= 0; i--){
         for(int k = i + 1; k <= i + 3 && k <= n; k++){
            dp[i] = max(dp[i], sum[i] - dp[k]);
         }
      }
      int total = sum[0];
      int x = dp[0];
      int y = total - x;
      return x > y? "Amal" : x == y ? "Tie" : "Bimal";
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,7};
   cout << (ob.stoneGameIII(v));
}

Input

{1,2,3,7}

Output

Bimal
raja
Published on 09-Jun-2020 10:45:05
Advertisements