![]() |
VOOZH | about |
Given the heights of n towers in the array heights[], the task is to make all towers the same height by either adding or removing blocks.
Each addition or removal operation has a different cost for each tower, specified in the array cost[].
The objective is to minimize the total cost required to equalize the heights of all towers.
Examples:
Input: heights[] = [1, 2, 3], cost[] = [10, 100, 1000]
Output: 120
Explanation: We try all possible target heights and calculate the cost to make all towers equal to that height. The minimum cost comes when we raise tower 1 by 2 and tower 2 by 1, totaling 120, which is the lowest among all options.
Input: heights[] = [7, 1, 5], cost[] = [1, 1, 1]
Output: 6
Explanation: 1 * abs(7-5) + 1 * abs(1-5) + 1 * abs(5-5) = 6
(Taking 5 as final height)
Table of Content
The idea is to iterate through each tower, and find the total cost of making heights of all towers to current tower. If total cost is less than current result, update the result.
120
At minimum or maximum heights, the cost increases due to many changes in heights. As we move toward a balanced height, the cost drops, reaches a minimum, then rises again — forming a V-shape. We use binary search by checking mid - 1, mid, and mid + 1 to move toward the side with lower cost and find the minimum cost efficiently.
Step by step approach:
120
At low or high heights, the cost increases due to excessive changes in heights. As we move toward an optimal height, the cost decreases, reaches a minimum, then increases again — forming a V-shape (unimodal pattern). This allows us to use Ternary search to efficiently find the minimum cost.
Step by step approach:
120
Time Complexity: O(n × log3(max(heights[i]) - min(heights[i]))), ternary search is applied over the range from the minimum to the maximum tower height. In each step, calculating the total cost takes O(n) time, and the number of steps is logarithmic in the height difference.
Auxiliary Space: O(1), the algorithm uses only a constant amount of extra variables for computation, regardless of the number of towers.