Topic: 100232. Minimum number of operations exceeding threshold II
Question description
Minimum number of operations exceeding threshold II
Given an array of integers starting from 0 nums and an integer k. You can do the following:
- Choose
numsThe smallest two integers inxandy。 - will
xandyfromnumsDelete in. - will
min(x, y) * 2 + max(x, y)Add to any position in the array.
Note that only if nums You can only perform the above operations if it contains at least two elements.
The goal is to make all elements in the array greater than or equal to k. Please return the minimum number of operations required to achieve this goal.
Example
Example 1:
- Input:
nums = [2,11,10,1,3], k = 10 - Output:
2 - Explanation: In the first operation, we remove elements 1 and 2 and then add 1_2 + 2 to
numsin,numsbecome[4, 11, 10, 3]. In the second operation, we remove elements 3 and 4 and add 3_2 + 4 tonumsin,numsbecome[10, 11, 10]. At this point, all elements in the array are greater than or equal to 10, so we stop. The minimum number of operations required is 2.
- Input:
Example 2:
- Input:
nums = [1,1,2,4,9], k = 20 - Output:
4 - Explanation: After the first operation,
numsbecome[2, 4, 9, 3]. After the second operation,numsbecome[7, 4, 9]. After the third operation,numsbecome[15, 9]. After the fourth operation,numsbecome[33]. At this point, all elements in the array are greater than or equal to 20, so we stop. The minimum number of operations required is 4.
- Input:
Tips
2 <= nums.length <= 2 * 10^51 <= nums[i] <= 10^91 <= k <= 10^9- The input guarantees that the answer must exist, that is to say, there must be a sequence of operations that makes all elements in the array greater than or equal to
k。
solution strategy
This problem can be solved efficiently by greedy algorithm and min-heap. We select the smallest two numbers from the array for operation each time, so that the sum of the numbers can be increased fastest and the threshold can be reached or exceeded faster. k. The steps are as follows:
initialization: Convert an array into a min-heap to quickly find the smallest two numbers.
perform operations: Repeat the following steps until all elements in the array are greater than or equal to
k:- Pop the smallest two elements from the heap
xandy。 - will
2 * min(x, y) + max(x, y)Added back to the pile. - Record the number of operations.
- Pop the smallest two elements from the heap
Return results: when all elements are greater than or equal to
kWhen , return the number of operations.
Code implementation
1 | import heapq |
This code uses Python's heapq Module to effectively manage the minimum heap to ensure that the smallest two numbers can be found quickly every time. In this way, we can solve this problem efficiently.