Skip to content

Instantly share code, notes, and snippets.

@aaani
Created November 2, 2013 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaani/7280435 to your computer and use it in GitHub Desktop.
Save aaani/7280435 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using namespace std;
int Max(int a, int b){
return a>b?a:b;
}
int Min(int a, int b){
return a<b?a:b;
}
//V[i] => Value of ith vount from the left
//M[i][j] => Maximum Possible Amount that a player can win for coins V[i],V[i+1],....V[j]
int maxScore(vector<int> V){
int M[V.size()][V.size()];
//Initialize matrix, diagonal elements are populated first
for(int i=0;i<V.size();i++){
M[i][i] = V[i];
if(i<V.size()-1) M[i][i+1] = Max(V[i],V[i+1]);
}
for(int i=2;i<V.size();i++){
for(int j=0;j<V.size()-i;j++){
M[j][j+i] = Max( V[j] + Min(M[j+2][j+i], M[j+1][j+i-1]), V[j+i] + Min(M[j+1][j+i-1], M[j][j+i-2]));
}
}
return M[0][V.size()-1];
}
//Testing code
int main(int argc, const char * argv[])
{
vector<int> piles={1,6,12,2,11,10};
cout<<maxScore(piles);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment