Skip to content

Commit f8f214a

Browse files
authored
Create 1349-maximum-students-taking-exam.js
1 parent 8753837 commit f8f214a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

1349-maximum-students-taking-exam.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {character[][]} seats
3+
* @return {number}
4+
*/
5+
const maxStudents = function (seats) {
6+
if (!seats.length) return 0
7+
const lastPos = 1 << seats[0].length
8+
const classroom = seats.map((row) =>
9+
row.reduce((a, c, i) => (c === '#' ? a : a | (1 << i)), 0)
10+
)
11+
const dp = new Array(seats.length + 1).fill(null).map(() => new Map())
12+
dp[0].set(0, 0)
13+
for (let row = 0; row < seats.length; row++) {
14+
let queue = [0]
15+
let numStudents = 0
16+
while (queue.length > 0) {
17+
const next = []
18+
for (let arrangement of queue) {
19+
let max = 0
20+
for (let [prevArrang, count] of dp[row]) {
21+
if (conflicts(prevArrang, arrangement)) continue
22+
max = Math.max(max, count + numStudents)
23+
}
24+
dp[row + 1].set(arrangement, max)
25+
for (let i = 1; i < lastPos; i <<= 1) {
26+
if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i)
27+
}
28+
}
29+
queue = next
30+
numStudents++
31+
}
32+
}
33+
return Math.max(...dp[seats.length].values())
34+
}
35+
function conflicts(prev, curr) {
36+
return prev & (curr << 1) || prev & (curr >> 1)
37+
}
38+
function canSit(row, arrangement, newStudent) {
39+
return (
40+
row & newStudent &&
41+
!(arrangement & newStudent) &&
42+
!(arrangement & (newStudent << 1)) &&
43+
!(arrangement & (newStudent >> 1))
44+
)
45+
}

0 commit comments

Comments
 (0)