본문 바로가기

0/leetcode

[October LeetCoding Challenge] 29th - Maximize Distance to Closest Person

반응형

leetcode.com/explore/challenge/card/october-leetcoding-challenge/563/week-5-october-29th-october-31st/3512/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

class Solution:
    def maxDistToClosest(self, seats: List[int]) -> int:
        
        output = 1
        prev = -1
        
        for i, s in enumerate(seats) :
            if s :
                if prev != -1 :
                    output = max(output, (i-prev)//2)
                else :
                    output = i
                prev = i
        
        output = max(output, len(seats)-1-prev)
        return output
    

정리 : 

세가지의 경우를 고려해야한다.

1. 왼쪽에 앉은 사람이 아무도 없을 경우

2. 오른쪽에 앉은 사람이 아무도 없을 경우

3. 양쪽에 사람이 있을 경우

첫번째 경우를 살펴보자. 왼쪽에 아무도 없기 때문에 처음으로 발견한 seat의 인덱스(가장 왼쪽에 앉아 있는 사람의 인덱스)가 우리가 구하고자 하는 답이 될 것이다.

두번째 경우를 살펴보자. 문제에서 적어도 한명은 앉아있다고 명시를 해놓았기 때문에 배열을 다돌고나면 prev는 가장 오른쪽에 있는 사람의 인덱스가 될 것이다. 이 경우에는 (배열의 마지막 인덱스 - 가장 오른쪽에 있는 사람의 인덱스)가 우리가 구하고자 하는 답이 될 것이다.

세번째 경우에는 양쪽에 사람이 있기 때문에 가운데에 앉는 경우가 된다. 이럴 경우에는 (현재 인덱스 - 바로 왼쪽에 앉아있는 사람의 인덱스)/2가 우리가 구하고자 하는 답이 될 것이다.

반응형

'0 > leetcode' 카테고리의 다른 글

139. Word Break 풀이  (0) 2020.11.17
5. Longest Palindromic Substring 풀이  (0) 2020.11.11
398. Random Pick Index  (0) 2020.10.27
388. Longest Absolute File Path  (0) 2020.10.27
914. X of a Kind in a Deck of Cards  (0) 2020.10.21