We are given an array with binary values named nums, this will return the max consecutive ones.
In order to solve this problem I am going to be using JavaScript.
As an example, the first array to be executed will be:
nums: [1,1,0,1,1,1] which will return the value: 3.
The following is the code to solve this problem:
var findMaxConsecutiveOnes = function(nums) {
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
for (let i=0; i<nums.length; i++) {
if (nums[i] === 1) {
c++;
}
if (nums[i] === 0 || i === (nums.length - 1)) {
if (l1 !== 0 && l2 < l1) {
l2 = l1;
}
l1 = c;
c = 0;
if (l1 > l2) {
largest = l1;
} else {
largest = l2;
}
}
}
console.log(largest);
return largest;
};
Now, I am going to explain the code:
var findMaxConsecutiveOnes = function(nums) {
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
};
First, we declare the function "findMaxConsecutiveOnes" e ititialize the variables c, l1, l2, and largest equal to 0.
var findMaxConsecutiveOnes = function(nums) {
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
for (let i=0; i<nums.length; i++) {
if (nums[i] === 1) {
c++;
}
};
Then we need to iterate through each element on the array nums. In orde to do this we utilize a for loop. At the same time, every time the index "i" is equal to 1 we'll increment the value of variable "c" by one.
var findMaxConsecutiveOnes = function(nums) {
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
for (let i=0; i<nums.length; i++) {
if (nums[i] === 1) {
c++;
}
if (nums[i] === 0 || i === (nums.length - 1)) {
l1 = c;
c = 0;
}
};
Now we ask: if index "i" is equal to 0, or index "i" indicates the end of the array then we should set the value of "l1" equal to the value of the accumulator variable "c". Then we reset the variable "c" to 0.
var findMaxConsecutiveOnes = function(nums) {
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
for (let i=0; i<nums.length; i++) {
if (nums[i] === 1) {
c++;
}
if (nums[i] === 0 || i === (nums.length - 1)) {
if (l1 !== 0 && l2 < l1) {
l2 = l1;
}
l1 = c;
c = 0;
}
}
};
Let's say the max consecutive ones in the array id equal to 2 and then we find that there is a new value, higher of consecutibe ones, then we should replace this value as the new max. In order to do this we inquiere whether the variable "l1" is not equal to 0 and also if "l1" is greater that "l2", then "l2" would be the value of "l1".
let c = 0;
let l1 = 0;
let l2 = 0;
let largest = 0;
for (let i=0; i<nums.length; i++) {
if (nums[i] === 1) {
c++;
}
if (nums[i] === 0 || i === (nums.length - 1)) {
if (l1 !== 0 && l2 < l1) {
l2 = l1;
}
l1 = c;
c = 0;
if (l1 > l2) {
largest = l1;
} else {
largest = l2;
}
}
}
console.log(largest);
return largest;
};
Finally, we figure out if the max consecutive ones of the newest found value "l1" is greater than the previous max value "l2". Then, we assign "l1" to "largest"; otherwise, "largest" will be equal to "l2". We the proceed to return the value of "largest", which will give us the final answer.