ROCK - Sweet and Sour Rock

A manufacturer of sweets has started production of a new type of sweet called rock. Rock comes in sticks composed of one-centimetre-long segments, some of which are sweet, and the rest are sour. Before sale, the rock is broken up into smaller pieces by splitting it at the connections of some segments.

Today's children are very particular about what they eat, and they will only buy a piece of rock if it contains more sweet segments than sour ones. Try to determine the total length of rock which can be sold after breaking up the rock in the best possible way.


The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of input contains one integer N - the length of the stick in centimetres (1<=N<=200). The next line is a sequence of N characters '0' or '1', describing the segments of the stick from the left end to the right end ('0' denotes a sour segment, '1' - a sweet one).


For each test case output a line with a single integer: the total length of rock that can be sold after breaking up the rock in the best possible way.


Sample input:

Sample output:

hide comments
chodermal: 2019-11-20 17:00:48

is there O(n) solution to this problem?

shubham97361: 2019-06-09 22:10:46

Good problem.

anshumanc007: 2018-12-19 11:01:19

can be solved in { time->0 (n^3) space ->0(n^2) } as well as { time-> 0(n^2) space->0(n) }.

a161112225: 2018-09-05 20:24:22

why i am getting WA and in which test case ? i am trying with partition DP (iterative )

aman_sachin200: 2018-06-14 00:10:48

Awesome One!!

kalyanavuthu: 2018-04-16 04:50:52

Last edit: 2018-04-16 04:51:33
sinersnvrsleep: 2018-01-18 13:49:54

o(n3) solution is very easy plz give hint of o(n2) solution;

ashishranjan28: 2017-05-25 09:47:06

recursion partitioning + memoisation

nilabja16180: 2017-03-29 10:56:34

AC in one GO!

cake_is_a_lie: 2017-02-23 03:32:49

This problem can be solved in O(N) time, so for example on my computer I can solve instances with N=1000000 in <0.1s.

The constraints here are so loose that they will even pass an O(N^3) solution like MCM, which is sad as it's much more interesting to get the O(N) solution.

For those interested in a hint, there's a fairly obvious DP solution in O(N^2) and with a clever implementation it can be made to run in O(N) amortized time and O(N) memory. The heart of the solution is 5 simple lines of code, so it's not exactly difficult to implement either.

Last edit: 2017-02-23 14:48:40

Added by:adrian
Time limit:7s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002