Binary Search | Efficient easy solution with explanation | C++ | Super Easy Approach
Please upvote if you found this helpfulIntuitionWhen given multiple mechanics with different ranks, we need to distribute the workload among them optimally. Sin
# **Please upvote if you found this helpful**

---


# Intuition
When given multiple mechanics with different ranks, we need to distribute the workload among them optimally. Since the time taken by a mechanic to repair cars follows a quadratic function, the goal is to find the minimum possible time where all cars can be repaired efficiently.

# Approach
1. **Binary Search on Time**:
   - We search for the minimum possible time using binary search between `1` and `ranks[0] * cars^2`.
   - The maximum possible time is assuming the worst mechanic (highest rank) repairs all cars.

2. **Checking Feasibility**:
   - For a given `mid` time, compute how many cars can be repaired by all mechanics using the formula:  
    ` repaired += sqrt(mid / r);`
   - If the total repaired cars is greater than or equal to `cars`, we reduce the search space.

3. **Efficiency**:
   - The binary search runs in O(log({max time}), and each feasibility check is O(n), leading to an overall complexity of O(Cars∗Log(N)), which is optimal.

# **Please upvote if you found this helpful**

---


# Complexity
- **Time complexity**: O(Cars∗Log(N))
- **Space complexity**: O(1) (only a few extra variables used)


![image.png](https://assets.leetcode.com/users/images/be3ae052-9b69-4c9b-b173-5c6522111985_1742106409.0610654.png)

# **Please upvote if you found this helpful**

---



# Code
```cpp []
class Solution {
public:
    long long repairCars(vector<int>& ranks, int cars) {
        long long left = 1, right = (long long)ranks[0] * cars * cars;
        
        while (left < right) {
            long long mid = left + (right - left) / 2;
            long long repaired = 0;
            
            for (int r : ranks) {
                repaired += sqrt(mid / r);
                if (repaired >= cars) break;
            }
            
            if (repaired >= cars) right = mid;
            else left = mid + 1;
        }
        return left;
    }
};
```
['C++']