# Analysis of PROB Broken Necklace

## Introduction

This is an analysis of PROB Broken Necklace, one of USA Computer Olympiad’s training problems.
Just doing some disposal on my old stuff.

## Description

You have a necklace of N red, white, or blue beads (3<=N<=350) some of which are red, others blue, and others white, arranged at random. Here are two examples for n=29:

            1 2                               1 2
r b b r                           b r r b
r         b                       b         b
r           r                     b           r
r             r                   w             r
b               r                 w               w
b                 b               r                 r
b                 b               b                 b
b                 b               r                 b
r               r                 b               r
b             r                   r             r
b           r                     r           r
r       r                         r       b
r b r                             r r w
Figure A                         Figure B


The beads considered first and second in the text that follows have been marked in the picture.

The configuration in Figure A may be represented as a string of b’s and r’s, where b represents a blue bead and r represents a red one, as follows: brbrrrbbbrrrrrbrrbbrbbbbrrrrb .

Suppose you are to break the necklace at some point, lay it out straight, and then collect beads of the same color from one end until you reach a bead of a different color, and do the same for the other end (which might not be of the same color as the beads collected before this).

Determine the point where the necklace should be broken so that the most number of beads can be collected.

## Analysis

Given an input string ‘wwwbbrwrbrbrrbrbrwrwwrbwrwrrb’, we concatenate it with itself, result in ‘wwwbbrwrbrbrrbrbrwrwwrbwrwrrbwwwbbrwrbrbrrbrbrwrwwrbwrwrrb’. This trick, working on handling minus or over-length index is easier.

1. Brute force solution.

For each index $a_i$ as a start, if $a_{i+1}$ can be picked into the longest substring, we pick it then do this again on $a_{i+1}$. Note that, if $a_i$ is w, we must treat it as b and r, one by one. We do N times of picking attempt for each $a_i$. Therefore complexity is O(N2). Just a straight forward solution.

2. DP solution.

We denote substring composed by successive r, which ends at index $i$ to $t_{i,r}$.

Similarly, we denote substring composed by successive b, which ends at index $i$ to $t_{i,b}$.

On the other hand, we denote substring composed by successive r, which starts at index $i$ to $s_{i,r}$.

And substring composed by successive b, which starts at index $i$ to $t_{i,b}$.

For each index $a_i$, $\max \{s_{i,r}, s_{i,b} \} + \max \{t_{i,r}, t_{i,b} \}$ is the length of longest substring if we break it at index $i$. We do this for N times, the greatest one is the answer. Complexity of this algorithm is O(n).