2727public class PredictTheWinner {
2828 private static boolean PredictTheWinner (int [] nums ) {
2929 int totalScore = 0 ;
30+
31+ // iterate through all the elements in an array to calculate the total possible score
3032 for (int i = 0 ; i < nums .length ; i ++) {
3133 totalScore += nums [i ];
3234 }
3335
36+ // initialize a 2-d dp array to store answers for sub problems
37+ // if the dp[i][j] is -1, that means we haven't calculated the answer for that particular subarray
38+ // if not, then we can simply return the value instead of recalculating it again
3439 int [][] dp = new int [nums .length ][nums .length ];
3540 for (int i = 0 ; i < nums .length ; i ++) {
3641 for (int j = 0 ; j < nums .length ; j ++ ) {
3742 dp [i ][j ] = -1 ;
3843 }
3944 }
4045
46+ // let's find out what is maximum score player 1 can get if plays optimally
4147 int player1Score = score (nums , 0 , nums .length - 1 , dp );
48+
49+ // similarly we can simply subtract it from total possible score to calculate the player 2 score
4250 int player2Score = totalScore - player1Score ;
51+
52+ // player 1 wins if the score is not lower than player 2 score
4353 return player1Score >= player2Score ;
4454 }
4555
4656 private static int score (int [] nums , int i , int j , int [][] dp ) {
4757 if (i > j ) return 0 ;
58+
59+ // this is the base case and for single element, nums[i] is the only possible score a player can get
4860 if (i == j ) return nums [i ];
4961
62+ // if we have already calculated the score for this subarray, then we don't need to recalculate it
63+ // and can return the one we stored in the 2d dp array
5064 if (dp [i ][j ] != -1 ) return dp [i ][j ];
5165
66+ // here a player can have two choice,
67+ // 1) player picks the number from left end
68+ // 2) or player picks the number from right end
69+ // check above for the detailed explaination about the recurrence
5270 int selectLeft = nums [i ] + Math .min (
5371 score (nums , i + 2 , j , dp ),
5472 score (nums , i + 1 , j - 1 , dp )
@@ -59,6 +77,7 @@ private static int score(int[] nums, int i, int j, int[][] dp) {
5977 score (nums , i + 1 , j - 1 , dp )
6078 );
6179
80+ // persist the optimal score in an dp array before returning it
6281 return dp [i ][j ] = Math .max (selectLeft , selectRight );
6382 }
6483
0 commit comments