To find the maximum number of consecutive 1s in a JavaScript array, follow this simple logic:
✅ Example Input:
const arr = [1, 1, 0, 1, 1, 1, 0, 1, 1];
✅ Goal:
Find the longest streak of consecutive
1s.
✅ Solution using for loop:
let maxCount = 0;
let currentCount = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
console.log("Maximum consecutive 1s:", maxCount);
✅ Output:
Maximum consecutive 1s: 3
🧠 Explanation:
currentCount: keeps track of the current streak of 1s.maxCount: stores the highest streak seen so far.- When you hit a
0, resetcurrentCount.