Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
find max Consecutive Ones in array using javascript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report

0

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).
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!