#P1203. Collecting Maximum Beads from a Necklace

    ID: 14135 Type: Default 1000ms 256MiB

Collecting Maximum Beads from a Necklace

Collecting Maximum Beads from a Necklace

You are given a necklace consisting of n beads. Each bead may be red (r), blue (b), or white (w). The beads are arranged in a circle in an arbitrary order (for example, see the image below for n = 29).

The necklace is represented by a string. For instance, one example is:

brbrrrbbbrrrrrbrrbbrbbbbrrrrb

To collect beads, you may break the necklace at any point, thereby turning it into a linear sequence. Then, starting from one end, you collect beads one by one until you encounter a bead that does not match the color you are collecting. You then turn to the other end and do the same process. When collecting beads, a white bead (w) is considered as a wildcard that can match either red or blue. Note that the collection from both ends does not overlap; if the sum of beads collected is more than n, then the answer is n.

Your task is to determine the maximum number of beads that can be collected by choosing an optimal breaking point.

In mathematical notation, if you break the necklace between positions i and i+1, let F be the number of beads collected by moving forward (wrapping around if necessary) and B be the number collected by moving backward. Then the number of beads collected is:

$\min\{n,\,F+B\}$

Choose the break point that maximizes this value.

inputFormat

The input consists of two lines:

  1. The first line contains an integer n (the number of beads on the necklace).
  2. The second line contains a string of length n that is made up of the characters r, b, and w, representing red, blue, and white beads respectively.

outputFormat

Output a single integer representing the maximum number of beads that can be collected.

sample

29
brbrrrbbbrrrrrbrrbbrbbbbrrrrb
8