Maximum consecutive one’s starting and ending index in a binary array in C++

Clash Royale CLAN TAG#URR8PPP
Maximum consecutive one’s starting and ending index in a binary array in C++
How to find the starting & ending position (or) index of the longest consecutive 1's in a binary array
EX: 110011110011 -> Starting position is 4 & Ending position is 7
What does the question have to do with C++ programming? It is clearly an algorithms question and the answer doesn't depend on the programming language used.
– PaulMcKenzie
Aug 10 at 5:11
2 Answers
2
Try this code:
#include<iostream>
#include<string>
using namespace std;
int main()
int longest = 0;
int stpos = 0;
int lpos = 0;
string s = "110011110011";
for(int i=0; i<s.length();)
char current = s[i];
int currLen = 0;
for(;i<s.length() && current == s[i]; ++i)
++currLen;
stpos = i;
if(currLen > longest)
longest = currLen ;
lpos = stpos;
cout<<"longest streak length:"<<longest<<endl;;
cout<<"starting index:"<<lpos-longest+1<<endl;
cout<<"ending index:"<<lpos<<endl;;
return 0;
The output is:
longest streak length:4
starting index:4
ending index:7
Thanks for the replying, could you please explain why the declaration was avoided in second for loop
– vinod kumar
Aug 10 at 5:38
@vinodkumar I want to initialize the second loop with the current value of 'i' coming from the first loop that's why it is not initialized. As an alternative, you can write 'for(i;i<s.length() && current == s[i]; ++i)'
– Saboor
Aug 10 at 5:53
Code is printing index of 0 if the string has more number of 0's than 1's, could you please help me out to print only the index for 1's
– vinod kumar
Aug 10 at 7:16
You can try this simple code.I assume the array if of length 12.
int arr[12];
int lower=0;
int upper=0;
int max_count=0;
int count=0;
for(int i=0;i<12;i++)
if(arr[i]==1)
count++;
else
if(max_count<count)
lower=i-count;
max_count=count;
upper=i-1;
count=0;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Just iterate through it and keep track of longest and current sequence of ones, and update longest when you find a longer sequence. But SO is not a code writing service, questions which just ask someone to write your code for you generally get downvoted and closed.
– hyde
Aug 10 at 5:09