Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda