#1947

Maximum Compatibility Score Sum

Medium
ArrayDynamic ProgrammingBacktrackingBit ManipulationBitmaskBacktrackingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n * m!)
Space
O(n)
O(m)
💡

Intuition

Time O(n * m!)Space O(m)

We can use backtracking with bit manipulation to efficiently explore the assignment of students to mentors without generating all permutations. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a function to calculate the compatibility score between a student and a mentor.
  2. 2Step 2: Use a backtracking approach to assign students to mentors, keeping track of which mentors have been used using a bitmask.
  3. 3Step 3: Recursively calculate the maximum score by trying to assign each student to each available mentor.
solution.py15 lines
1def maxCompatibilitySum(students, mentors):
2    def compatibility(student, mentor):
3        return sum(s == m for s, m in zip(student, mentor))
4
5    def backtrack(student_index, used_mask):
6        if student_index == len(students):
7            return 0
8        max_score = 0
9        for mentor_index in range(len(mentors)):
10            if not (used_mask & (1 << mentor_index)):
11                score = compatibility(students[student_index], mentors[mentor_index])
12                max_score = max(max_score, score + backtrack(student_index + 1, used_mask | (1 << mentor_index)))
13        return max_score
14
15    return backtrack(0, 0)

Complexity note: The time complexity is O(n * m!) because we explore all possible assignments of students to mentors, where n is the number of students and m is the number of mentors. The space complexity is O(m) due to the bitmask used to track mentor assignments.

  • 1Understanding bit manipulation can significantly optimize the solution.
  • 2Backtracking helps explore all combinations without generating all permutations explicitly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.