Cinema Seat Allocation

A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.

Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.

Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.

 

Example 1:

Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
Output: 4
Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.

Example 2:

Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
Output: 2

Example 3:

Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
Output: 4

 

Constraints:


Solution:

class Solution {
    public int maxNumberOfFamilies(int n, int[][] reservedSeats) {
        Map<Integer, Set<Integer>> reserved = new HashMap();
        for (int[] r : reservedSeats) {
            reserved.computeIfAbsent(r[0], k -> new HashSet());
            reserved.get(r[0]).add(r[1]);;
        }
        // System.out.println(reserved);
        int result = 0;
        for (Map.Entry<Integer, Set<Integer>> entry : reserved.entrySet()) {
            Set<Integer> r = entry.getValue();
            boolean one = true, two = true, three = true;
            for (int j = 2; j <= 5; j ++) {
                if (r.contains(j)) {
                    one = false;
                }
            }
            for (int j = 4; j <= 7; j ++) {
                if (r.contains(j)) {
                    two = false;
                }
            }
            for (int j = 6; j <= 9; j ++) {
                if (r.contains(j)) {
                    three = false;
                }
            }
            // System.out.println(i + ", " + one + ", " + two + ", " + three);
            if (one && three) {
                result += 2;
            } else if (two) {
                result += 1;
            } else if (one || three) {
                result += 1;
            }
        }
        result += (n - reserved.size()) * 2;
        return result;
    }
}