Stone Game

Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

Example 1:

Input: piles ={5,3,4,5}
Output: true

Approach

Java


public class StoneGame {
    public static void main(String[] args) {
        int[] piles = { 5345 };
        System.out.println(stoneGame(piles));
    }

    static int dp[][];

    static int stoneGame(int lint rint[] piles) {
        if (dp[l][r] != 0)
            return dp[l][r];
        if (r - l == 1)
            dp[l][r] = Math.max(piles[l], piles[r]);
        else
            dp[l][r] = Math.max(piles[l] + stoneGame(l + 1, r, piles), 
                    piles[r] + stoneGame(l, r - 1, piles));
        return dp[l][r];
    }

    static boolean stoneGame(int[] piles) {
        int n = piles.length;
        int sum = 0;
        dp = new int[510][501];
        for (int i = 0; i < n; i++)
            sum += piles[i];
        int alex = stoneGame(0, n - 1, piles);
        if (alex > sum - alex)
            return true;
        return false;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int dp[510][501];
int stoneGame(int l,int r,vector<int&piles)
{
        if(dp[l][r]!=-1)
              return dp[l][r];
        if(r-l==1)
              dp[l][r]= max(piles[l],piles[r]);
        else
              dp[l][r]=max(piles[l]+stoneGame(l+1,r,piles),piles[r]+stoneGame(l,r-1,piles));
        return dp[l][r];
}
bool stoneGame(vector<int>& piles
{
        int n=piles.size();
        int sum=0;
        memset(dp,-1,sizeof(dp));
        for(int i=0;i<n;i++)
              sum+=piles[i];
        int alex=stoneGame(0,n-1,piles);
         if(alex>sum-alex)
               return true;
        return false;
}

int main()
{
    vector<intpiles ={5,3,4,5};
    if(stoneGame(piles))
      cout<<"true";
    else
      cout<<"false";

    return 0;
    
    
}


No comments:

Post a Comment