Leetcode 2357. Make Array Zero by Subtracting Equal Amounts
You are given a non-negative integer array nums. In one operation, you must:
x that is present in the array.x from every positive element of the array.Return the minimum number of operations required to make every element of the array equal to 0.
The idea is based on the observation that each unique positive number in the array must be used at least once as x in the operations to eventually reduce all elements to zero.
Key Insights:
n is the number of elements in the array. This is because we iterate through the array once to populate the set.#include <vector>
#include <unordered_set>
int minimumOperations(std::vector<int>& nums) {
std::unordered_set<int> uniqueValues;
for (int num : nums) {
// Insert the number into the set if it's not zero
if (num != 0) {
uniqueValues.insert(num);
}
}
// The size of the set represents the number of different values subtracted.
return uniqueValues.size();
}
unordered_set to keep track of unique non-zero elements.This approach ensures we count each unique value only once, giving us the minimum number of required operations.
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?