1. Binary Search + Greedy

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:
            # Get the middle index between left and right boundary indexes.
            # cur_sweetness stands for the total sweetness for the current person.
            # people_with_chocolate stands for the number of people that have 
            # a piece of chocolate of sweetness greater than or equal to mid.  
            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

Time & Space Complexity

  • Time complexity: O(nlog(S/(k+1)))O(n \cdot \log(S/(k + 1)))

    • The lower and upper bounds are min(sweetness) and S / (k + 1) respectively. In the worst case (when k is small), the right boundary will have the same magnitude as S, and the left boundary will be 1. Thus, the maximum possible time complexity for a single binary search is O(logS)O(\log S).
      For every single search, we need to traverse the chocolate bar in order to allocate chocolate chunks to everyone, which takes O(n)O(n) time.
  • Space complexity: O(1)O(1) constant space

Where nn is the number of chunks in the chocolate, and SS is the total sweetness of the chocolate bar.