Program to find minimum number of bricks required to make k towers of same height in Python

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 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 towers with heights [7, 14, 31] and make them all height 31, requiring (31-7) + (31-14) + (31-31) = 24 + 17 + 0 = 41 bricks. Actually, a better selection would be [4, 7, 14] made to height 14, requiring (14-4) + (14-7) + 0 = 17 bricks.

Algorithm Approach

The key insight is that for k consecutive towers (after sorting), the optimal target height is the maximum height among those k towers. We use a sliding window approach to find the minimum cost ?

  • Sort the list heights
  • ans := infinity
  • s := 0 (running sum of current window)
  • For each index i and value x in heights, do
    • s := s + x
    • If i >= k, then remove the leftmost element: s := s - heights[i - k]
    • If i >= k - 1, then we have k elements, calculate cost: ans := minimum of ans and (x * k - s)
  • Return ans

Implementation

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

# Test the solution
ob = Solution()
heights = [5, 8, 32, 15, 41]
k = 3
result = ob.solve(heights, k)
print(f"Heights: {heights}")
print(f"k = {k}")
print(f"Minimum bricks needed: {result}")
Heights: [5, 8, 32, 15, 41]
k = 3
Minimum bricks needed: 17

How It Works

After sorting heights = [5, 8, 15, 32, 41], the algorithm considers each possible group of k=3 consecutive towers ?

  • Group [5, 8, 15]: Target height 15, cost = 15*3 - (5+8+15) = 45 - 28 = 17
  • Group [8, 15, 32]: Target height 32, cost = 32*3 - (8+15+32) = 96 - 55 = 41
  • Group [15, 32, 41]: Target height 41, cost = 41*3 - (15+32+41) = 123 - 88 = 35

The minimum cost is 17 bricks.

Step-by-Step Example

def solve_with_details(heights, k):
    print(f"Original heights: {heights}")
    heights.sort()
    print(f"Sorted heights: {heights}")
    
    ans = float("inf")
    s = 0
    
    for i, x in enumerate(heights):
        s += x
        if i >= k:
            s -= heights[i - k]
            print(f"Window moved: removed {heights[i - k]}, sum = {s}")
        
        if i >= k - 1:
            cost = x * k - s
            ans = min(ans, cost)
            window = heights[max(0, i-k+1):i+1]
            print(f"Window {window}: target={x}, cost={cost}, min_so_far={ans}")
    
    return ans

# Detailed example
heights = [5, 8, 32, 15, 41]
k = 3
result = solve_with_details(heights, k)
print(f"\nMinimum bricks needed: {result}")
Original heights: [5, 8, 32, 15, 41]
Sorted heights: [5, 8, 15, 32, 41]
Window [5, 8, 15]: target=15, cost=17, min_so_far=17
Window moved: removed 5, sum = 23
Window [8, 15, 32]: target=32, cost=41, min_so_far=17
Window moved: removed 8, sum = 47
Window [15, 32, 41]: target=41, cost=35, min_so_far=17

Minimum bricks needed: 17

Conclusion

This sliding window approach efficiently finds the minimum bricks needed by considering all possible consecutive groups of k towers. The time complexity is O(n log n) due to sorting, and space complexity is O(1).

Updated on: 2026-03-25T12:32:14+05:30

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements