Cinema Seat Allocation LeetCode solution in Java

1
class Solution {
2
public int maxNumberOfFamilies(int n, int[][] reservedSeats) {
3
Map<Integer, int[]> seats = new HashMap<>();
4
int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots
5

6
for (int[] seat : reservedSeats) {
7
int row = seat[0];
8
int col = seat[1];
9
int[] slots = seats.getOrDefault(row, new int[3]);
10

11
if (col >= 2 && col <= 5) { // left slot
12
slots[0] = 1;
13
}
14
if (col >= 4 && col <= 7) { // middle slot
15
slots[1] = 1;
16
}
17
if (col >= 6 && col <= 9) { // right slot
18
slots[2] = 1;
19
}
20

21
seats.put(seat[0], slots);
22
}
23

24
for (int[] slots : seats.values()) {
25
int taken = slots[0] + slots[2];
26

27
if (taken == 2) { // both slots at either ends are taken
28
if (slots[1] == 0) { // check if middle slot not taken
29
availableSlots--; // reduce availableslots by 1 since middle slot is available
30
} else {
31
availableSlots -= 2; // entire row not available - reduce by 2
32
}
33
} else if (taken == 1) { // one of the slots at either ends are taken
34
availableSlots--; // reduce by 1 since either side of the slots not available
35
} else {
36
continue; // entire row is available - no need to reduce the available slots
37
}
38
}
39

40
return availableSlots;
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0