Friday, 25 October 2013

Topcoder SRM 595 DIV2 250

Problem Statement


In short, You are given a string containing only characters R,G,B. We can remove the string from either end at each move( from left or from right). Finally, the string must contain only R or G or B.

You can find a detailed problem description here.


Solution


The solution is much simple. We need to keep track of maximum number of consecutive characters at every point. Let MAX be the size of maximum consecutive characters finally.

Minimum no. of moves == String Length - MAX

CODE


[sourcecode language="cpp"]
class LittleElephantAndBallsAgain {
public:
int getNumber(string s) {
int sz = s.size();
int cnt = 1;
int max = 1;
char color = s[0];
for(int i = 1;i<sz;i++)
{
if( s[i] == color )
cnt++;
else
{
if( cnt > max )
max = cnt;
cnt = 1;
color = s[i];
}
}
if( cnt > max )
max = cnt;
return (sz - max);
}
};
[/sourcecode]

No comments:

Post a Comment