Skip to content

Commit 372aa7c

Browse files
committed
add a solution for Predict the winner problem
1 parent bf3caaf commit 372aa7c

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

LeetCode/PredictTheWinner.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.io.BufferedReader;
2+
import java.io.IOException;
3+
import java.io.InputStreamReader;
4+
import java.util.Arrays;
5+
6+
/*
7+
* Problem:
8+
* Given an array of integers of size `n`. Now 2 players are playing a game with this array.
9+
* They make their turn alternatively and in each turn, they pick a number from either end and add it to their score.
10+
* If player 1 gets more or equal score than the player 2, player 1 wins otherwise player 2 wins.
11+
* Both players play the game optimally.
12+
*
13+
* Approach: Dynamic Programming
14+
* As we know both players play optimally,
15+
* If a player pick an element from either end then next player will also try to maximize the score and will try to minimize other player's score
16+
* So for subarray `i` and `j`, the recurrence would be,
17+
* dp[i][j] = Math.max(
18+
* a[i] + Math.min(dp[i + 1][j - 1], dp[i + 2][j]),
19+
* a[j] + Math.min(dp[i + 1][j - 1], dp[i][j - 2])
20+
* )
21+
* and base case would be dp[i][i] = a[i]
22+
* Complexity:
23+
* Time complexity = O(n * n) // as we have 2 dp states, the complexity is squared
24+
* Space complexity = O(n * n) // as we are calculating an answer for each subarray, the complexity is also squared
25+
*/
26+
27+
public class PredictTheWinner {
28+
private static boolean PredictTheWinner(int[] nums) {
29+
int totalScore = 0;
30+
for(int i = 0; i < nums.length; i++) {
31+
totalScore += nums[i];
32+
}
33+
34+
int[][] dp = new int[nums.length][nums.length];
35+
for(int i = 0; i < nums.length; i++) {
36+
for(int j = 0; j < nums.length; j++ ) {
37+
dp[i][j] = -1;
38+
}
39+
}
40+
41+
int player1Score = score(nums, 0, nums.length - 1, dp);
42+
int player2Score = totalScore - player1Score;
43+
return player1Score >= player2Score;
44+
}
45+
46+
private static int score(int[] nums, int i, int j, int[][] dp) {
47+
if(i > j) return 0;
48+
if(i == j) return nums[i];
49+
50+
if(dp[i][j] != -1) return dp[i][j];
51+
52+
int selectLeft = nums[i] + Math.min(
53+
score(nums, i + 2, j, dp),
54+
score(nums, i + 1, j - 1, dp)
55+
);
56+
57+
int selectRight = nums[j] + Math.min(
58+
score(nums, i, j - 2, dp),
59+
score(nums, i + 1, j - 1, dp)
60+
);
61+
62+
return dp[i][j] = Math.max(selectLeft, selectRight);
63+
}
64+
65+
public static void main(String[] args) throws IOException {
66+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
67+
int n = Integer.parseInt(br.readLine());
68+
69+
int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
70+
71+
System.out.println(PredictTheWinner(array));
72+
}
73+
}

0 commit comments

Comments
 (0)