LeetCode 1349: Maximum Students Taking Exam Solution
Master LeetCode problem 1349 (Maximum Students Taking Exam), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1349. Maximum Students Taking Exam
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming with bit masking. We iterate through each row of the classroom and for each row, we check all possible combinations of students sitting in the row without cheating. We use bit masking to represent the state of each row and store the maximum number of students that can be seated without cheating in a 2D dp array.
For each row, we iterate through all possible combinations of students and check if the current combination is valid (no cheating). If it is valid, we update the dp array with the maximum number of students that can be seated in that row.
Finally, we return the maximum value from the last row of the dp array as the result.
Time complexity: O(m * 2^n * 2^n), where m is the number of rows and n is the number of columns. Space complexity: O(m * 2^n), where m is the number of rows and n is the number of columns.
Solution Code
class Solution {
public int maxStudents(char[][] seats) {
int m = seats.length;
int n = seats[0].length;
int[][] dp = new int[m][1 << n];
for (int i = 0; i < m; i++) {
for (int mask = 0; mask < (1 << n); mask++) {
if (isValid(seats, i, mask, n)) {
for (int prevMask = 0; prevMask < (1 << n); prevMask++) {
if ((prevMask & (mask << 1)) == 0 && ((prevMask << 1) & mask) == 0) {
dp[i][mask] = Math.max(dp[i][mask], dp[i - 1][prevMask] + Integer.bitCount(mask));
}
}
}
}
}
int maxStudents = 0;
for (int mask = 0; mask < (1 << n); mask++) {
maxStudents = Math.max(maxStudents, dp[m - 1][mask]);
}
return maxStudents;
}
private boolean isValid(char[][] seats, int row, int mask, int n) {
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0 && seats[row][i] == '#') {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1349 (Maximum Students Taking Exam)?
This page provides optimized solutions for LeetCode problem 1349 (Maximum Students Taking Exam) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1349 (Maximum Students Taking Exam)?
The time complexity for LeetCode 1349 (Maximum Students Taking Exam) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1349 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1349 in Java, C++, or Python.