Leetcode 3038. Maximum Number of Operations With the Same Score I
You are given an array nums
of integers. You can perform the following operation any number of times:
i
and j
such that nums[i] = nums[j]
and i != j
.nums[i]
and nums[j]
from the array.Your task is to determine the maximum number of operations you can perform.
0
.The strategy revolves around counting the frequency of each element in the array. For any element, the number of pairs that can be formed is equal to the integer division of its frequency by 2
.
Here are the steps:
HashMap
to count the frequency of each number in the array.2
.Let’s implement this in Java:
import java.util.HashMap;
public class MaximumOperations {
public int maxOperations(int[] nums) {
HashMap<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int maxOperations = 0;
for (int frequency : frequencyMap.values()) {
maxOperations += frequency / 2;
}
return maxOperations;
}
public static void main(String[] args) {
MaximumOperations solution = new MaximumOperations();
int[] nums = {1, 2, 3, 4, 4, 3, 2, 1};
System.out.println(solution.maxOperations(nums)); // Output: 4
}
}
n
is the number of elements in the nums
array.m
is the number of unique elements in the nums
array. Since m
is at most n
in the worst case, this step is also ( O(n) ).Overall, the time complexity is ( O(n) ). The space complexity is also ( O(n) ) due to the HashMap
storing the frequency counts.
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?