#1349

Maximum Students Taking Exam

Hard
ArrayDynamic ProgrammingBit ManipulationMatrixBitmaskBit ManipulationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n * m)
O(m * 2^n * 2^n)
Space
O(1)
O(2^n)
💡

Intuition

Time O(m * 2^n * 2^n)Space O(2^n)

The optimal solution uses dynamic programming with bit masking to efficiently calculate the maximum number of students that can be seated without cheating. By representing the seating arrangement as a bitmask, we can quickly check for valid placements based on previous rows.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i] represents the maximum number of students that can be seated up to row i.
  2. 2Step 2: For each row, iterate through all possible bitmasks representing the seating arrangement.
  3. 3Step 3: For each bitmask, check if it is valid based on the previous row's bitmask and update the DP array accordingly.
solution.py13 lines
1# Full working Python code
2def maxStudents(seats):
3    m, n = len(seats), len(seats[0])
4    dp = [0] * (1 << n)
5    for i in range(m):
6        new_dp = dp[:]
7        for mask in range(1 << n):
8            if all(seats[i][j] == '.' for j in range(n) if (mask & (1 << j))):
9                for prev in range(1 << n):
10                    if (mask & prev) == 0 and not any((prev & (1 << (j - 1))) and (mask & (1 << j)) for j in range(1, n)):
11                        new_dp[mask] = max(new_dp[mask], dp[prev] + bin(mask).count('1'))
12        dp = new_dp
13    return max(dp)

Complexity note: The time complexity is O(m * 2^n * 2^n) because for each row (m), we check all combinations of previous and current row seating arrangements (2^n). The space complexity is O(2^n) due to the DP array storing results for each bitmask.

  • 1Bit manipulation allows efficient representation of seating arrangements.
  • 2Dynamic programming can optimize the selection of valid student placements.

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