Find maximum height to cut all chocolates horizontally such that at least K amount remains
Given an array arr consisting of heights of N chocolate bars, the task is to find the maximum height at which the horizontal cut is made to all the chocolates such that the sum remaining amount of chocolate is at least K.
Input: K = 7, arr = [15, 20, 8, 17]
Suppose a cut is made at height 8:
-> chocolate taken from 1st chocolate bar = 15 – 8 =7
-> chocolate taken from 2nd chocolate bar = 20 – 8 =12
-> chocolate taken from 3rd chocolate bar = 8 – 8 = 0
-> chocolate taken from 4th chocolate bar = 17 – 8 = 9
=> Total chocolate wasted = (7 + 12 + 0 + 9) – K = 28 – 7 = 21
Suppose a cut is made at height 15:
-> chocolate taken from 1st chocolate bar = 15 – 15 = 0
-> chocolate taken from 2nd chocolate bar = 20 – 15 = 5
-> 3rd chocolate bar wont be chosen as it is less than 15
-> chocolate taken from 4th chocolate bar = 17 – 15 = 2
=> Total chocolate wasted = (0 + 5 + 2) – K = 7 – 7 = 0
Therefore when we take chocolate of height 15 then chocolate wasted is minimum. Therefore 15 is the answer.
Input: K = 12, arr = [30, 25, 22, 17, 20]
After a cut at height 18, the chocolate removed is 25 and chocolate wastage is (25 – 12) = 13 units. But if the cut is made at height 21 is made then 14 units of chocolate is removed and the wastage is (14 – 12) = 2 which is the least, hence 21 is the answer
Approach: The given problem can be solved based on Binary Search.
The idea is to perform the Binary Search over then range [0, max element of the array] and find that value in the range, say M, such that the sum of remaining chocolate after making the horizontal cut at M gives minimum difference with K.
Follow the steps below to solve the given problem:
- Initialize two variables, say low and high as 0 and the maximum array element respectively.
- Iterate until low <= high and perform the following steps:
- Find the value of mid as (low + high)/2.
- Find the sum of remaining chocolates after making the horizontal cut at height mid as M.
- If the value of M is less than K, then update the value of high as (mid – 1). Otherwise, update the value of low as (mid + 1).
- After performing the above steps, print the value as high as the resultant maximum height that must be cut.
Below is the implementation of the above approach:
Time Complexity: O(N*log N)
Auxiliary Space: O(1)