C++ Program to Minimize the maximum difference between heights
October 11, 2022
Minimize the maximum difference between heights in C++
Here, in this page we will discuss the program to minimize the maximum difference between heights in C++ . We are Given with heights of n towers and a value k. We need to either increase or decrease the height of every tower by k (only once) where k > 0. Our task is to minimize the difference between the heights of the longest and the shortest tower after modifications and output this difference.
Algorithm :
Take the size of the array from the user and store it in a variable say n and take the value of K and store it in another variable say k.
Now declare an array of size n and take n elements of the array from the user.
Now, create one function to perform the required operation.
First, we try to sort the array and make each height of the tower maximum.
We do this by decreasing the height of all the towers towards the right by k and increasing all the height of the towers towards the left (by k).
It is also possible that the tower you are trying to increase the height doesn’t have the maximum height.
Therefore we only need to check whether it has the maximum height or not by comparing it with the last element towards the right side which is a[n]-k.
Since the array is sorted if the tower’s height is greater than the a[n]-k then it’s the tallest tower available.
Similar reasoning can also be applied for finding the shortest tower.
Login/Signup to comment