Leetcode 3065. Minimum Operations to Exceed Threshold Value I
You are given an array nums
consisting of positive integers. You must perform operations to reduce the size of the array by repeatedly removing the largest element until the average of the elements in the array becomes strictly greater than a given threshold x
. You need to return the minimum number of operations required to achieve this.
The average of an array is the sum of its elements divided by its size.
nums
is a positive integer.x
is a positive integer or float.x
?
x
, zero operations should be performed, so the function should return 0
.x
, return 0
.x
.The primary operations involve repeatedly removing the maximum element and updating the sum, both of which can be handled efficiently with a max heap. The time complexity will be O(n log n)
due to the max heap operations.
Here is the C++ code to solve the problem:
#include <iostream>
#include <vector>
#include <queue>
#include <numeric>
using namespace std;
int minOperationsToExceedThreshold(vector<int>& nums, double x) {
// Calculate initial sum and average
double sum = accumulate(nums.begin(), nums.end(), 0.0);
double average = sum / nums.size();
// If the initial average is already greater than x, return 0
if (average > x) {
return 0;
}
// Create a max heap for the numbers
priority_queue<int> maxHeap(nums.begin(), nums.end());
int operations = 0;
while (!maxHeap.empty() && average <= x) {
// Remove the largest element
int maxElement = maxHeap.top();
maxHeap.pop();
// Update sum and size of array
sum -= maxElement;
operations++;
// Recalculate the average
average = sum / (nums.size() - operations);
}
return operations;
}
int main() {
vector<int> nums = {10, 20, 5, 3, 15};
double x = 7.0;
cout << "Minimum operations: " << minOperationsToExceedThreshold(nums, x) << endl;
return 0;
}
0
immediately.x
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?