Skip to content

Instantly share code, notes, and snippets.

@tblancog
Created January 21, 2017 01:24
Show Gist options
  • Save tblancog/82397cb696c8242978cfdc36be3e91f5 to your computer and use it in GitHub Desktop.
Save tblancog/82397cb696c8242978cfdc36be3e91f5 to your computer and use it in GitHub Desktop.
Max Consecutive Ones
/**
485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
**/
var input= [1,0,1,1,1,0];
var counter= 0; // Ones counter
var lastValue= null; // Start lastValue as null
for(var i=0; i< input.length; i++){
if( input[i] === 1 // Is current element 1?
&& lastValue === input[i] // AND is consecutive with previous element?
|| (lastValue === null && input[i] === 1) // OR the first element is null? lastValue= null means i'm at first element
){
// Raise counter by 1
counter++;
}
// Now point last value as current element
lastValue= input[i];
}
// Since i can't console.log i write on the document
document.write("<h1>Consecutive ones: <span class=\"label label-primary\">"+ counter +"</span> <h1/>" );
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment