Minimum Operations to Exceed Threshold Value II - Problem

You are given a 0-indexed integer array nums, and an integer k. You are allowed to perform some operations on nums, where in a single operation, you can:

  • Select the two smallest integers x and y from nums.
  • Remove x and y from nums.
  • Insert (min(x, y) * 2 + max(x, y)) at any position in the array.

Note that you can only apply the described operation if nums contains at least two elements.

Return the minimum number of operations needed so that all elements of the array are greater than or equal to k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,11,10,1], k = 10
Output: 3
💡 Note: Operation 1: combine 1,2 → 1×2+2=4, array=[4,11,10]. Operation 2: combine 4,10 → 4×2+10=18, array=[18,11]. Operation 3: combine 11,18 → 11×2+18=40, array=[40]. All elements ≥ 10, so 3 operations needed.
Example 2 — Already Valid
$ Input: nums = [1,1,2,4,9], k = 1
Output: 0
💡 Note: All elements are already ≥ 1, so no operations needed.
Example 3 — Single Small Element
$ Input: nums = [1,1,2,4,9], k = 20
Output: 4
💡 Note: Need multiple operations to combine small elements until all reach threshold 20.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Minimum Operations to Exceed Threshold Value II INPUT nums array: 2 [0] 11 [1] 10 [2] 1 [3] k = 10 Use Min-Heap: 1 2 10 11 ALGORITHM STEPS 1 Pop x=1, y=2 1*2+2=4, ops=1 heap: [4,10,11] 2 Pop x=4, y=10 4*2+10=18, ops=2 heap: [11,18] 3 Pop x=11, y=18 11*2+18=40, ops=3 heap: [40] 4 Check condition min(heap) = 40 40 >= 10 -- OK Operation Formula: min(x,y)*2 + max(x,y) Time: O(n log n) Space: O(n) FINAL RESULT After 3 operations: [40] OK 40 >= k (10) All elements satisfy the threshold! Output: 3 Operations performed: 3 Key Insight: Use a min-heap to always access the two smallest elements efficiently. Each operation combines them using min(x,y)*2 + max(x,y), which guarantees the result is always greater than both inputs. Continue until the minimum element in the heap is >= k. The heap ensures O(log n) per operation. TutorialsPoint - Minimum Operations to Exceed Threshold Value II | Optimal Solution
Asked in
Google 25 Meta 20 Amazon 18
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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