Longest Equal-Letter Subsequence
National Olympiad — Municipal round (2024 season)
Submission name: maxsub.cpp
Problem summary
Select a longest subsequence consisting of one repeated lowercase letter. Ties favour the alphabetically earlier letter. Selected positions need not be consecutive.
Input
One lowercase word.
Output
The selected repeated-letter word.
Constraints
1≤word length≤200.
Worked example
Input and output for the worked example discussed below.
Input
bbabab
Output
bbbb
Solution analysis
- For one chosen letter, keep every occurrence. Gaps do not matter for a subsequence, so the best attainable length is its frequency rather than its longest contiguous run.
- Count all letters in 26 counters. Scan from a to z, replacing the best letter only when its count is strictly larger; equal counts preserve the earlier letter.
- For bbabab, a occurs twice and b four times, giving bbbb. In ayzyayzz, y and z both occur three times, so the tie rule selects yyy.
Why it works
All occurrences of a chosen letter form a valid subsequence, and no longer subsequence of that letter exists. Maximizing its count therefore maximizes the answer length; strict updates enforce the alphabetical tie-break.
Watch out. Do not confuse a subsequence with a contiguous substring. Updating on equal counts favours the wrong tied letter.
Commented C++17 solution
An independently written complete program with standard headers.
#include<array>
#include<iostream>
#include<string>
using namespace std;
int main(){
string word;
cin>>word;
array<int,26>counts{};
for(char letter:word){
counts[letter-'a']++;
}
int best=0;
for(int letter=1;letter<26;letter++){
// Strict improvement preserves the earlier tied letter.
if(counts[letter]>counts[best]){
best=letter;
}
}
cout<<string(counts[best],char('a'+best))<<'\n';
}