Minimum Number of Seconds to Make Mountain Height Zero - Problem

You are given an integer mountainHeight denoting the height of a mountain. You are also given an integer array workerTimes representing the work time of workers in seconds.

The workers work simultaneously to reduce the height of the mountain. For worker i:

  • To decrease the mountain's height by x, it takes workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x seconds.

For example:

  • To reduce the height of the mountain by 1, it takes workerTimes[i] seconds.
  • To reduce the height of the mountain by 2, it takes workerTimes[i] + workerTimes[i] * 2 seconds, and so on.

Return an integer representing the minimum number of seconds required for the workers to make the height of the mountain 0.

Input & Output

Example 1 — Basic Case
$ Input: mountainHeight = 4, workerTimes = [2,1,1]
Output: 3
💡 Note: Worker 1 reduces 1 unit (time: 2), Worker 2 reduces 2 units (time: 1+2=3), Worker 3 reduces 1 unit (time: 1). Maximum time is 3.
Example 2 — Single Worker
$ Input: mountainHeight = 3, workerTimes = [3]
Output: 18
💡 Note: Only worker reduces all 3 units: 3×1 + 3×2 + 3×3 = 3 + 6 + 9 = 18 seconds.
Example 3 — Equal Workers
$ Input: mountainHeight = 5, workerTimes = [1,1]
Output: 6
💡 Note: Optimal distribution: Worker 1 gets 3 units (1+2+3=6), Worker 2 gets 2 units (1+2=3). Maximum time is 6.

Constraints

  • 1 ≤ mountainHeight ≤ 105
  • 1 ≤ workerTimes.length ≤ 104
  • 1 ≤ workerTimes[i] ≤ 106

Visualization

Tap to expand
Mountain Height Reduction Problem INPUT Height: 4 workerTimes Array 2 W0 1 W1 1 W2 Time for x height reduction: t*(1+2+...+x) = t*x*(x+1)/2 mountainHeight = 4 workerTimes = [2,1,1] ALGORITHM STEPS 1 Init Priority Queue (nextTime, worker, reduced) 2 Push Initial States Each worker: (t[i], i, 1) 3 Pop Min, Update Decrease height, push next 4 Repeat Until Done Height becomes 0 Priority Queue States: Step Pop Height Time Init - 4 0 1 W1(1s) 3 1 2 W2(1s) 2 1 3 W0(2s) 1 2 4 W1(3s) 0 3 W1: 1+2=3s for 2 units FINAL RESULT Ground Level Work Timeline (0-3s) 0s 1s 2s 3s W0: -1 height (2s) W1: -1 -1 (1+2=3s) W2: -1 Output: 3 [OK] Minimum seconds = 3 W0: 1, W1: 2, W2: 1 Total: 1+2+1 = 4 height Key Insight: Use a min-heap to always pick the worker who can complete their next unit of work earliest. For worker i reducing x units: time = workerTimes[i] * (1+2+...+x) = workerTimes[i] * x*(x+1)/2. The greedy approach ensures parallel workers finish in minimum time by optimal work distribution. TutorialsPoint - Minimum Number of Seconds to Make Mountain Height Zero | Greedy with Priority Queue
Asked in
Google 15 Microsoft 12 Amazon 10 Meta 8
28.0K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen