관리 메뉴

서랍장

leetcode 1231 본문

algorithm

leetcode 1231

소소한 프로그래머 2022. 10. 26. 20:40

 

class Solution:
    def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
        # Initialize the left and right boundaries.
        # left = 1 and right = (total sweetness) / (number of people).
        number_of_people = k + 1
        left = min(sweetness)
        right = sum(sweetness) // number_of_people
        
        while left < right:

            mid = (left + right + 1) // 2
            cur_sweetness = 0
            people_with_chocolate = 0
            
            # Start assigning chunks to the current person.
            for s in sweetness:
                cur_sweetness += s
                
                # If the total sweetness is no less than mid, this means we can break off
                # the current piece and move on to assigning chunks to the next person.
                if cur_sweetness >= mid:
                    people_with_chocolate += 1
                    cur_sweetness = 0

            if people_with_chocolate >= k + 1:
                left = mid
            else:
                right = mid - 1
                
        return right

'algorithm' 카테고리의 다른 글

leetcode 1060, 1901  (0) 2022.10.26
leetcode 1662  (0) 2022.10.25
leetcode 189  (0) 2022.10.25
leetcode 1239  (0) 2022.10.24
binary search 이분 탐색  (0) 2022.10.23
Comments