Maximum Compatibility Score Sum — LeetCode 1947 Python Solution

MediumBit ManipulationArrayDynamic ProgrammingBacktrackingBitmask
Problem
#1947
Reading time
5 min

The problem

There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1.

Example

Input
students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]
Output
8
Explanation
We assign students to mentors in the following way:

Python solution

Python
class Solution:
    def maxCompatibilitySum(
        self, students: List[List[int]], mentors: List[List[int]]
    ) -> int:
        def dfs(i: int, s: int):
            if i >= m:
                nonlocal ans
                ans = max(ans, s)
                return
            for j in range(m):
                if not vis[j]:
                    vis[j] = True
                    dfs(i + 1, s + g[i][j])
                    vis[j] = False

        ans = 0
        m = len(students)
        vis = [False] * m
        g = [[0] * m for _ in range(m)]
        for i, x in enumerate(students):
            for j, y in enumerate(mentors):
                g[i][j] = sum(a == b for a, b in zip(x, y))
        dfs(0, 0)
        return ans

Complexity

MeasureComplexity
TimeO(m!)
SpaceO(m^2) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1947. Maximum Compatibility Score Sum is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1947. Maximum Compatibility Score Sum?
LeetCode 1947. Maximum Compatibility Score Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 1947. Maximum Compatibility Score Sum?
The Python solution on this page runs in O(m!).
What is the space complexity of LeetCode 1947. Maximum Compatibility Score Sum?
The Python solution on this page uses O(m^2) auxiliary space.
What topics does LeetCode 1947. Maximum Compatibility Score Sum cover?
LeetCode 1947. Maximum Compatibility Score Sum is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview