The description is rather long, but the problem is incredibly simple. Here's my paraphrase:
Given a list of integers, find the product of the most frequent three (part 1) and the least frequent three (part 2).
This can be done in two parts: calculating the frequency of those integers and ranking them.
Calculating the frequency: As these numbers are sparse, we use a hashmap to keep track of their frequency. Simply iterate over the numbers as keys; if exist, we increment the count by one, otherwise insert one (as we have already encoutered it). A well implemented hashmap with minimal collision should give amortised
Ranking those numbers: We can sort them naively with an efficient in place sort for (frequency, value) pair (assuming dictionary ordering), then we pop the top element if the heap size grows beyond three; the time complexity would be
If generality is not of any concern, you can manually maintain the largest/smallest values in three variables, which would have an even lower overhead.
Code:
max_3_prod :: (xs : List Int @ owned) -> Int {
m @ mut :: HashMap Int Int ();
for i in xs {
m.update i ((x : Int) -> Int {x + 1}) 1
}
pq @ mut :: PriorityQueue (Int, Int) ();
for e in m.entries () {
pq.push (*e.1, *e.0);
if (pq.len () > 3) {
pq.pop ();
}
}
r @ mut :: 1;
for i in 0..3 {
pair :: (pq.pop ()).unwrap ();
num :: pair.1;
r *= num;
}
r
};