#3296
Minimum Number of Seconds to Make Mountain Height Zero
MediumArrayMathBinary SearchGreedyHeap (Priority Queue)Binary SearchGreedyHeap
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log m)Space O(1)
The optimal solution uses binary search to efficiently find the minimum time required. We check if a given time is sufficient to reduce the mountain height to zero by calculating the total reduction possible within that time.
⚙️
Algorithm
4 steps- 1Step 1: Define a function to check if a given time can reduce the mountain height to zero.
- 2Step 2: Use binary search to find the minimum time by setting a range from 1 to a large enough value.
- 3Step 3: For each mid-point in the binary search, calculate the total height reduction possible by all workers within that time.
- 4Step 4: Adjust the search range based on whether the height can be reduced to zero.
solution.py23 lines
1# Full working Python code
2
3def can_reduce_to_zero(time, mountainHeight, workerTimes):
4 total_reduction = 0
5 for time_per_worker in workerTimes:
6 x = 1
7 while time_per_worker * x * (x + 1) // 2 <= time:
8 total_reduction += x
9 x += 1
10 if total_reduction >= mountainHeight:
11 return True
12 return total_reduction >= mountainHeight
13
14
15def min_seconds_optimal(mountainHeight, workerTimes):
16 left, right = 1, 10**9
17 while left < right:
18 mid = (left + right) // 2
19 if can_reduce_to_zero(mid, mountainHeight, workerTimes):
20 right = mid
21 else:
22 left = mid + 1
23 return leftℹ
Complexity note: The time complexity is O(n log m) where n is the number of workers and m is the maximum time we are searching through, as we check each worker's contribution in logarithmic steps.
- 1Workers can work simultaneously, so we need to consider the maximum time taken by any worker.
- 2The contribution of each worker increases quadratically with the amount they reduce the mountain.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.