Leetcode 2357. Make Array Zero by Subtracting Equal Amounts
You are given a non-negative integer array nums
. In each operation, you must:
x
such that x
is less than or equal to the smallest non-zero element of nums
.x
from every positive element of nums
.Return the minimum number of operations required to make every element in nums
equal to 0
.
Input: nums = [1,5,0,3,5]
Output: 3
Input: nums = [0]
Output: 0
nums
?
nums
could be anywhere from 0 to 10^5.nums
take?
nums
are non-negative integers and can range from 0 to 10^9.nums
is already all zeroes?
nums
is already all zeroes, the number of operations required is 0.nums
contain duplicate numbers?
nums
can contain duplicate numbers.To solve the problem, we need to make every element in the array nums
equal to 0 using the least number of operations described.
One efficient approach is to understand that each unique positive number in the array nums
must eventually be reduced to zero. Hence, the number of operations required to make the entire array zero is equivalent to the number of unique positive integers in the array.
nums
.import java.util.HashSet;
import java.util.Set;
public class MakeArrayZero {
public int minimumOperations(int[] nums) {
Set<Integer> uniquePositives = new HashSet<>();
for (int num : nums) {
if (num > 0) {
uniquePositives.add(num);
}
}
// The count of unique positive numbers is the number of operations required.
return uniquePositives.size();
}
public static void main(String[] args) {
MakeArrayZero maZero = new MakeArrayZero();
int[] nums1 = {1, 5, 0, 3, 5};
System.out.println(maZero.minimumOperations(nums1)); // Output: 3
int[] nums2 = {0};
System.out.println(maZero.minimumOperations(nums2)); // Output: 0
}
}
The total time complexity of this approach is O(n) where n
is the number of elements in the array nums
.
Hence, the overall time complexity is O(n), and this approach is efficient given the constraints of the problem.
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?