Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 16, 2025 19:24
Show Gist options
  • Save Ifihan/5fc8b8371b99dbf1bfb2543c5b57ab57 to your computer and use it in GitHub Desktop.
Save Ifihan/5fc8b8371b99dbf1bfb2543c5b57ab57 to your computer and use it in GitHub Desktop.
Minimum Time to Repair Cars

Question

Approach

I use a binary search approach to determine the minimum time needed to repair all cars. The search range is from 1 to the maximum possible repair time, calculated as min(ranks) * cars^2. The helper function canRepairWithinTime(t) checks if the given time t allows enough cars to be repaired.

Implementation

class Solution:
    def repairCars(self, ranks: List[int], cars: int) -> int:
        left, right = 1, min(ranks) * cars * cars
        
        def canRepairWithinTime(t: int) -> bool:
            total_cars = sum(int((t // r) ** 0.5) for r in ranks)
            return total_cars >= cars
        
        while left < right:
            mid = (left + right) // 2
            if canRepairWithinTime(mid):
                right = mid
            else:
                left = mid + 1
        
        return left

Complexities

  • Time: O(n log max_time)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment