Skip to content

Commit b36e404

Browse files
committed
Leetcode | Maximum Compatibility Score Sum | Java
1 parent 35f87d1 commit b36e404

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

leetcode/src/main/java/com/devstromo/medium/p1947/Solution.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,35 @@ public int maxCompatibilitySum(int[][] students, int[][] mentors) {
3636

3737
return dp[(1 << m) - 1];
3838
}
39+
40+
public int maxCompatibilitySumBest(int[][] students, int[][] mentors) {
41+
int m = students.length;
42+
Integer[] dp = new Integer[(1 << m) + 1];
43+
return helper(students, mentors, 0, 0, dp);
44+
}
45+
46+
private int find(int[] arr, int[] brr) {
47+
int res = 0;
48+
for (int i = 0; i < arr.length; i++) {
49+
res += (1 - (arr[i] ^ brr[i]));
50+
}
51+
return res;
52+
}
53+
54+
private int helper(int[][] students, int[][] mentors, int mask, int index, Integer[] dp) {
55+
int m = students.length;
56+
int n = students[0].length;
57+
if (index == m)
58+
return 0;
59+
int res = 0;
60+
if (dp[mask] != null)
61+
return dp[mask];
62+
for (int i = 0; i < m; i++) {
63+
if (((mask >> i) & 1) == 0)
64+
res = Math.max(find(students[index], mentors[i]) + helper(students, mentors, mask | (1 << i), index + 1, dp), res);
65+
}
66+
return dp[mask] = res;
67+
}
68+
69+
3970
}

leetcode/src/test/java/com/devstromo/medium/p1947/SolutionUnitTest.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,33 @@ void testMaximumCompatibilityScoreSum() {
3636
}
3737
));
3838
}
39+
40+
@Test
41+
@DisplayName("Test Maximum Compatibility Score Sum Best")
42+
void testMaximumCompatibilityScoreSumBest() {
43+
assertEquals(8, solution.maxCompatibilitySumBest(
44+
new int[][]{
45+
{1, 1, 0},
46+
{1, 0, 1},
47+
{0, 0, 1}
48+
},
49+
new int[][]{
50+
{1, 0, 0},
51+
{0, 0, 1},
52+
{1, 1, 0}
53+
}
54+
));
55+
assertEquals(0, solution.maxCompatibilitySumBest(
56+
new int[][]{
57+
{0, 0},
58+
{0, 0},
59+
{0, 0},
60+
},
61+
new int[][]{
62+
{1, 1},
63+
{1, 1},
64+
{1, 1},
65+
}
66+
));
67+
}
3968
}

0 commit comments

Comments
 (0)