imashutosh51

Aggresive Cows

Feb 14th, 2026 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. '''
  2. See two cows can be closest as 1 because even we are having the continous stalls and cows can be farthest when one is sitting at start of the stalls and other at the end of stalls so range of distance can be 1 to max(stalls)-min(stalls).
  3. we will be using the binary search on this range and check what is the maximum value of mid where we can place all the K cows.even we got the mid satisfying the condition, we still need to keep looking for more mid/distance values because we have to get the maximum distance between the closest placed cows.
  4.  
  5. Trick:
  6. Return the high from the binary search because high is the biggest value where binary search worked and low already crossed the high
  7. '''
  8. def count_cows(stalls, target):
  9.     #here count_cows check how many cows can be placed where dis bw them >=mid
  10.     cnt=1
  11.     cur=stalls[0]
  12.     for i in stalls[1:]:
  13.         if i-cur>=target:
  14.             cur=i
  15.             cnt+=1
  16.     return cnt
  17.    
  18. class Solution:
  19.     def aggressiveCows(self, stalls, k):
  20.         stalls.sort()
  21.         if len(stalls)<k:
  22.             return -1
  23.         #so our range is gonna be the distance which we need to maximise
  24.         #so Min distance can be 1 and max can be arr[-1]-arr[0]
  25.         l=1
  26.         r=stalls[-1]-stalls[0]
  27.         while l<=r:
  28.             mid= (l+r)//2
  29.             cnt=count_cows(stalls, mid)
  30.             # print(l,r,mid,cnt)
  31.             if cnt>=k: #if count>k means more cows can be placed so we can increase the distance
  32.                 l=mid+1 #even cnt==k still we can try to check on bigger values of max_distance.
  33.             else:
  34.                 r=mid-1
  35.         return r
  36.        
Advertisement
Add Comment
Please, Sign In to add comment