파비의 매일매일 공부기록

2023.02.22 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.22 Today's Challenge

fabichoi 2023. 2. 22. 23:45

https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

 

Capacity To Ship Packages Within D Days - LeetCode

Capacity To Ship Packages Within D Days - A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor

leetcode.com

이런 문제를 바이너리 서치를 통해 풀 수 있고만..

class Solution:
    def shipWithinDays(self, weights: List[int], days: int) -> int:
        l, r = max(weights), sum(weights)

        def shipDays(shipCapacity: int) -> int:
            days = 1
            capacity = 0
            for weight in weights:
                if capacity + weight > shipCapacity:
                    days += 1
                    capacity = weight
                else:
                    capacity += weight
            return days
        
        while l < r:
            m = (l + r) // 2
            if shipDays(m) <= days:
                r = m
            else:
                l = m + 1        
        return l
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.02.24 Today's Challenge  (0) 2023.02.24
2023.02.23 Today's Challenge  (0) 2023.02.23
2023.02.21 Today's Challenge  (0) 2023.02.21
2023.02.20 Today's Challenge  (0) 2023.02.20
2023.02.19 Today's Challenge  (0) 2023.02.19
Comments