Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Cake Distribution Problem

Hard Acceptance 64.62% Points 40

John is hosting a birthday party, and his friends have brought him a cake with N chunks, where each chunk has a certain level of sweetness represented by an array. To share the cake, John cuts it into K + 1 pieces, one for each of his K friends and one for himself. Since John is considerate, he decides to take the piece with the minimum sweetness for himself. Your task is to determine the maximum possible sweetness that John can receive when he distributes the cake in this way.

You need to complete the maxSweetness() function which takes an integer array of sweetness, an integer N and an integer K as the input parameters and returns an integer denoting the maximum sweetness that the John can get.

Examples
Example 1

Example 1

Input: N = 5, K = 1, sweetness[] = {1, 2, 3, 4, 5}

Output: 6

Explanation: Using binary search, we maximize the minimum sweetness John gets, and the best partition is [1,2,3] (6) & [4,5] (9), where John takes 6.

Example 2

Example 2

Input: N = 4, K = 1, sweetness[] = {10, 20, 30, 40}

Output: 40

Explanation: The best partition is [10,20,30] (60) & [40] (40), where John takes the minimum 40.

Constraints
  • 1 <= N <= 10^5
  • 0 <= K < N
  • 1 <= sweetness[i] <= 10^9
Hints
  • Expected Time Complexity: O(NlogM), where M is the sum of elements in the array.
  • Expected Space Complexity: O(1)
Topics
Array Searching Algorithms
Companies
Microsoft Walmart Qualcomm
Added 10 Mar 2025 64.62% acceptance
Ln 1, Col 1Sign in to save your code
5 1
1 2 3 4 5
6