코테, 알고리즘

[LeetCode] 2187. Minimum Time to Complete Trips

bereben 2023. 3. 7. 14:25

문제

제약사항

  • 1 <= time.length <= 10**5
  • 1 <= time[i], totalTrips <= 10**7

totalTrips를 채우는데 필요한 최소 시간을 구하는 문제. 이진탐색을 사용하면 간단히 풀 수 있다.
그러나 나는 당연하게도 한번만에 문제를 풀지 못했다.ㅋㅋㅋ
생각없이 ans를 습관적으로 10e9로 했는데 원소와 totalTrips의 최대 10의 7승이니 두개를 곱하면 10의 14제곱이 된다. 그래서 10의 15제곱으로 변경 후 제출했다.


코드

class Solution:
    def minimumTime(self, time: List[int], totalTrips: int) -> int:
        pl = 0
        pr = totalTrips * min(time)
        ans = 10e15
        while pl <= pr:
            pc = (pl + pr) // 2
            total = 0
            for i in time:
                total += pc // i
                if totalTrips > total:
                    pl = pc + 1
                else:
                    pr = pc - 1
                    ans = min(ans, pc)
        return ans