A binary array is just a list of numbers where every value is either 0 or 1. Nothing else is allowed. Think of it like a row of light switches, where 1 means "on" and 0 means "off".
Our task is simple to say: look through the array and find the longest unbroken streak of 1's. By "unbroken" we mean the 1's sit right next to each other, with no 0 between them. We then return how long that longest streak is.
Take this array:
arr = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
Let's walk along it and notice the groups of 1's:
1, 1, 1 → a streak of 3.0s break the chain.1, 1, 1, 1 → a streak of 4.The biggest streak we saw is 4, so the answer is 4.
Now the second example:
arr = [1, 1, 0, 0, 0, 1, 1, 0, 1, 0]
1, 1 → streak of 2.1, 1 → streak of 2.1 → streak of 1.The longest is 2, so the answer is 2.
You do not need to remember the whole array or do anything fancy. You only need to walk through it once, keeping track of two simple things:
count — how long the current streak of 1's is *right now*.maxCount — the longest streak you have seen *so far*.Here is the plain rule for each number as you pass over it:
1, the streak continues, so add one to count. Then check: if count is now bigger than maxCount, update maxCount to match it.0, the streak is broken. Reset count back to 0 and keep moving.When you reach the end of the array, maxCount holds the answer.
This works because count always tells you the length of the streak you are currently inside, and maxCount quietly remembers the best one you ever entered. A single pass is enough, which makes this both easy to write and fast to run.
The problem gives you a function shell to complete:
class Solution {
public:
int consecutiveOnes(vector<int> &arr) {
}
};
Inside consecutiveOnes, you would create your count and maxCount variables (both starting at 0), loop through every element of arr applying the rule above, and finally return maxCount.