Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Can anyone help me reduce the space complexity of this code for finding 4 adjacent seats in a row

$
0
0

Cinema Seat Allocation (https://leetcode.com/problems/cinema-seat-allocation/description/)image of 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.

the logic is perfectly good, but it takes more space.

My code :

class Solution(object):    def find(self, row):        str1 = "".join(map(str, row))  # Concatenate the integers in the row list        ans = 0        i = 0        while i < len(str1) - 4:            if str1[i:i + 4] == "0000" and i % 2 != 0:                ans += 1                i += 4            else:                i += 1        return ans    def maxNumberOfFamilies(self, n, reservedSeats):"""        :type n: int        :type reservedSeats: List[List[int]]        :rtype: int"""        ans = 0        cinema = [[0] * 10 for _ in range(n)]        for li in reservedSeats:            cinema[li[0] - 1][li[1] - 1] = 1        for row in cinema:            ans += self.find(row)        return ans

Example 1:

Seats looks like this:

Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]Output: 4Explanation: 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: 2Example 3:

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


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>