Finding the optimal solution may require some thought. Maybe it is also more effort than first assumed. If I have interpreted it correctly, the longest subsequence with more ones than zeros is to be found in the given repeating number sequence "0 1 1 0 0 0 1...".
As usual, one should first know what the correct result is. For the given example, the longest subsequence with more ones than zeros seems to be the sequence "1 0 1 1 0" with a length of 5.
So since results can contain the end and the beginning of the sequence you could simplify the search by doubling the sequence first.
std::string sequence = "01100001";
sequence += sequence;
Then it would be advisable to write a function that checks whether a partial sequence contains a solution. Based on simple strings it could look like this.
int hasMoreOnes(const std::string& sequence, int left, int right)
{
int ones_count = 0;
int zeros_count = 0;
bool valid = true;
for (int i = left; valid && (i <= right); ++i) {
switch (sequence[i]) {
case '0':
zeros_count++; break;
case '1':
ones_count++; break;
default:
valid = false; }
}
return ones_count - zeros_count;
}
Since there are several possible locations, one could remember them and compare them at the end.
For an optimized solution, however, the comparison of the current length with the largest found length of a partial sequence is sufficient. For tracing and debugging it can be useful to output all locations. A possible solution would be to search for a current 1 in each case and to increase the range to the right and left until the condition is no longer fulfilled. The total length is then the distance between the right and left index. At the end the result can be simply written out:
std::string sequence = "01100001"; std::cout << "Examine sequence:" << sequence << "..." <<sequence << "\n";
std::cout << "Max. subsequence length: " << find_max_adjacent_subsequence(sequence) << std::endl;