#3002
Medium Algorithms Maximum size of a set after removals
Array Hash Table Greedy
46.1% acceptance
Feb 25, 2026
323
30
You are given two 0-indexed integer arrays nums1 and nums2 of even length n.
You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals, you insert the remaining elements of nums1 and nums2 into a set s.
Return the maximum possible size of the set s.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn maximum_set_size(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
use std::collections::HashSet;
let n = nums1.len();
let half = n / 2;
let set1: HashSet<i32> = nums1.into_iter().collect();
let set2: HashSet<i32> = nums2.into_iter().collect();
let common = set1.intersection(&set2).count();
let only1 = set1.len() - common;
let only2 = set2.len() - common;
let k1 = only1.min(half);
let k2 = only2.min(half);
let common_kept = common.min((half - k1) + (half - k2));
(k1 + k2 + common_kept) as i32
}
}