Home > Blockchain >  find max Consecutive Ones in array using javascript
find max Consecutive Ones in array using javascript

Time:06-05

I have an array of numbers. I need to find the maximum number of consecutive 1s in the array.

var arr = [1, 1, 3, 2, 3, 1, 1, 1];

const maxOne = (arr) => {
  for (var i = 0; i < arr.length; i  ) {
    let count = 0;
    let result = 0;
    if (arr[i] ==1) {
      count  = 1;
      result = Math.max(result, count);
    } else {
      count = 0
    }
  return result
  }
}

console.log(maxOne(arr));

desired output: 3

my output : 1

I am not sure where I am going wrong

CodePudding user response:

You algorithm works, you just did few misstakes:

  • create variables outside of loop
  • return after loop, not in it(it will break loop at first iteration)
const maxOne = (arr) => {
  let count = 0;
  let result = 0;
  for (var i = 0; i < arr.length; i  ) {
    if (arr[i] === 1) {
      count  = 1;
      result = Math.max(result, count);
    } else {
      count = 0
    }
  }
  return result
}

CodePudding user response:

You can do like this.

let arr=[1,2,3,1,1,2,1,1,12,1,1,1,1];
let count=0;
for(let i=0;i<arr.length;i  ){
  arr[i]==1 ? count =1 :count=0;
}
console.log(count).
  • Related