Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Given an array arr[] denoting heights of N towers and a positive integer K.
- For each tower, you must perform exactly one of the following operations exactly once.
- Increase the height of the tower by K.
- 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)
- Find out the minimum possible difference between the height of the shortest and tallest towers after you have modified each tower.
- '''
- class Solution:
- def getMinDiff(self, arr, n, k):
- arr.sort()
- res = arr[-1]-arr[0]
- n=len(arr)
- #We have to decrease the right end must
- #we have to increase the left end must.Both are must. Because we want to reduce difference
- #Now we choose any two consecutive elements
- #X,Y we will increase X and decrease Y so that we minimise the our target.
- #To compare target we need to findout temp min and temp max after modifying the array values.
- #After modifying we will compare the tmax tmin diff and take mimimum of both.
- for i in range(1,n):
- X=arr[i]
- Y=arr[i-1]
- if arr[i]<k: #since in question he gave height cant be negative we shall skip it
- 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]
- tmax = max(arr[-1]-k , Y+k)#you need not do max oparr[i]-k because we know arr[i]<arr[-1]
- res=min(res,tmax-tmin)
- return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement