Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Cake Distribution Problem

Hard Acceptance 64.62% Points 40.00

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.

Hints
Hint 1
Expected Time Complexity: O(NlogM), where M is the sum of elements in the array.
Hint 2
Expected Space Complexity: O(1)
Constraints
  • 1 <= N <= 10^5
  • 0 <= K < N
  • 1 <= sweetness[i] <= 10^9
Companies
Microsoft Walmart Qualcomm
Topics
Array Searching Algorithms
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions