Back to Blogs
USACOCompetitive ProgrammingFrequency CountingGreedyJune 3, 2026

USACO 2025 More Cow Photos: Frequency Maps and Greedy Counting

How a recent USACO counting problem turns a list of photo values into a frequency map and then applies a compact greedy rule.

More Cow Photos is a reminder that sometimes the order of input values is not the useful information. The useful information is how many times each value appears.

Build a frequency map

When a problem asks about groups, duplicates, or repeated values, first ask whether a frequency table would simplify the story.

Map<Integer, Integer> count = new HashMap<>();
for (int x : values)
{
    count.put(x, count.getOrDefault(x, 0) + 1);
}

After this step, the input list is transformed into value counts. That makes rules about pairs and leftover values easier to express.

Look for the special maximum value

In this problem style, the largest key receives special handling. The code first gives credit for values with at least two appearances, then adjusts based on the count of the maximum value.

for each frequency:
    if frequency >= 2:
        answer += 2

if maxValue appears once:
    answer += 1
if maxValue appears at least twice:
    answer -= 1

The exact story matters, but the reusable habit is this: after counting frequencies, identify whether any boundary value has a different rule.

Common mistakes

  • Trying to sort and scan when a map gives the needed counts directly.
  • Forgetting that the maximum key may need separate handling.
  • Counting every duplicate group the same way even when the largest value is special.
  • Not testing cases with one occurrence and two occurrences of the maximum.

Practice prompt

Use the values [2, 2, 4, 5, 5, 5]. Build the frequency map, identify the maximum key, and apply the counting rule above by hand.