#C6072. Longest Alternating Subsequence

    ID: 49792 Type: Default 1000ms 256MiB

Longest Alternating Subsequence

Longest Alternating Subsequence

Given an integer \(N\) and a string \(S\) of length \(N\) consisting of lowercase English alphabets, your task is to find the length of the longest subsequence of \(S\) that can be formed by alternating between two distinct characters.

A subsequence is a sequence that can be derived from the string by deleting some or no elements without changing the order of the remaining characters. The alternating condition means that if the two characters chosen are \(a\) and \(b\), then the subsequence should be of the form \(a, b, a, b, \ldots\) (or \(b, a, b, a, \ldots\)). Note that a valid alternating subsequence must contain at least 2 characters.

Examples:

Input:
5
abbab
Output:
4

Input: 7 abcabc Output: 4

</p>

Hint: Consider each pair of distinct characters and simulate a greedy selection from the input string to build the alternating sequence. If the sequence built contains less than 2 characters, then ignore it.

inputFormat

The input consists of two lines:

  1. The first line contains an integer \(N\), the length of the string \(S\).
  2. The second line contains the string \(S\) consisting of lowercase English letters.

outputFormat

Output a single integer representing the length of the longest valid alternating subsequence. If no valid alternating subsequence exists, output 0.

## sample
5
abbab
4