Created
February 9, 2019 23:51
-
-
Save ramannanda9/382c26cdfacbd4152910aa2f656d7b70 to your computer and use it in GitHub Desktop.
Stones Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StonesProblem { | |
int[][] stageScore=null; | |
public boolean stoneGame(int[] piles) { | |
stageScore= new int[piles.length+2][piles.length+2]; | |
// stoneGameRec(0, piles, true,0,piles.length-1)>0 | |
return stoneGameBottomUp(piles)>0; | |
} | |
public int stoneGameRec(int sumSoFar, int [] piles, boolean positive, int begin, int end){ | |
if(stageScore[begin][end]!=0){ | |
return stageScore[begin][end]; | |
} | |
if(begin < end){ | |
int first = positive ? piles[begin]: -piles[begin]; | |
int last= positive ? piles[end]: piles[end]; | |
int result=-1; | |
if(positive) { | |
result=Math.max(stoneGameRec(sumSoFar+first,piles,!positive, begin+1,end), | |
stoneGameRec(sumSoFar+last,piles,!positive,begin,end-1)); | |
} | |
else{ | |
result=Math.min(stoneGameRec(sumSoFar+first,piles,!positive, begin+1,end), | |
stoneGameRec(sumSoFar+last,piles,!positive,begin,end-1)); | |
} | |
stageScore[begin][end]=result; | |
return result; | |
} | |
else return sumSoFar; | |
} | |
public int stoneGameBottomUp(int [] piles){ | |
int N = piles.length; | |
for(int k=1; k<=N; k++) { | |
for(int i=0; i+k <= N ;i++){ | |
int j = i + k -1; | |
boolean positive= ((j + i) % 2 == 1); | |
if(positive){ | |
stageScore[i+1][j+1]= Math.max(piles[i]+stageScore[i+2][j+1],piles[j]+stageScore[i+1][j]); | |
} | |
else{ | |
stageScore[i+1][j+1]= Math.min(-piles[i]+stageScore[i+2][j+1],-piles[j]+stageScore[i+1][j]); | |
} | |
} | |
} | |
System.out.println(stageScore[1][N]); | |
return stageScore[1][N]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment