Suppose we have a list of tower heights, and a positive value k. We want to select k towers and make them all the same height by adding more bricks, but using as few bricks as possible. We have to find the minimum number of bricks are needed to pick k towers and make them the same height.
So, if the input is like heights = [4, 7, 31, 14, 40] k = 3, then the output will be 17, as we can select 5, 8, and 15 which requires 17 bricks to make the same height.
To solve this, we will follow these steps −
- sort the list heights
- ans := infinity
- s := 0
- for each index i and value x in heights, do
- s := s + x
- if i >= k, then
- s := s - heights[i - k]
- if i >= k - 1, then
- ans := minimum of ans and (x * k - s)
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, heights, k): heights.sort() ans = float("inf") s = 0 for i, x in enumerate(heights): s += x if i >= k: s -= heights[i - k] if i >= k - 1: ans = min(ans, x * k - s) return ans ob = Solution() heights = [5, 8, 32, 15, 41] k = 3 print(ob.solve(heights, k))
Input
[5, 8, 32, 15, 41], 3
Output
17