Advertisement
Iam_Sandeep

Minimise the heights

Jul 28th, 2022
697
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1.  
  2. '''
  3. Given an array arr[] denoting heights of N towers and a positive integer K.
  4.  
  5. For each tower, you must perform exactly one of the following operations exactly once.
  6.  
  7. Increase the height of the tower by K.
  8. Decrease the height of the tower by K ( you can do this operation only if the height of the tower is greater than or equal to K)
  9. Find out the minimum possible difference between the height of the shortest and tallest towers after you have modified each tower.
  10. '''
  11.  
  12. class Solution:
  13.     def getMinDiff(self, arr, n, k):
  14.         arr.sort()
  15.         res = arr[-1]-arr[0]
  16.         n=len(arr)
  17.         #We have to decrease the right end  must
  18.         #we have to increase the left end must.Both are must. Because we want to reduce difference
  19.         #Now we choose any two consecutive elements
  20.         #X,Y we will increase X and decrease Y so that we minimise the our target.
  21.         #To compare target we need to findout temp min and temp max after modifying the array values.
  22.         #After modifying we will compare the tmax tmin diff and take mimimum of both.
  23.         for i in range(1,n):
  24.             X=arr[i]
  25.             Y=arr[i-1]
  26.             if arr[i]<k: #since in question he gave height cant be negative we shall skip it
  27.             tmin = min(arr[0]+k , X-k )#you need not do min op arr[i-1]+k because we know arr[i-1]<arr[i]
  28.             tmax = max(arr[-1]-k , Y+k)#you need not do max oparr[i]-k because we know arr[i]<arr[-1]
  29.             res=min(res,tmax-tmin)
  30.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement