0

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

10
  • 2
    Your code re-initializes result for each array element. It should not do that. Commented Jun 4, 2022 at 13:57
  • maximum number of consecutive .. and yet 3 is never consecutive from your input sample of arr? Commented Jun 4, 2022 at 13:57
  • 1
    @mardubbles there are three 1 values at the end of the array? Commented Jun 4, 2022 at 13:58
  • 1
    Ahh so 1s is not a noun, and is literal. I see Commented Jun 4, 2022 at 13:59
  • 2
    Also, the function should probably return result instead of print it. Commented Jun 4, 2022 at 14:00

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

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).

2 Comments

The . character at the end of the last line should be a ;, making it: console.log(count);.
That was just a typo @GustavoSousa
0
const numbers = [1,1,0,0,1,1,1,0,1];
const maxString = Math.max(...numbers.join('').split('0')); // remove zero items and convert 
// the sequential Ones to a string. After that Find the string with the largest number of characters.
console.log('max:', maxString.toString().length) // Take the string length
//3
you can use *Math.max.apply(Math, numbers.join('').split('0'))* instead of second line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.