485. Max Consecutive Ones
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the maximum number of consecutive 1s in a given binary array. This means we need to scan the array and keep track of the length of sequences of 1s, ultimately returning the longest length found.
Solution
Max Consecutive Ones in Python
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
max_count = 0
current_count = 0
for num in nums:
if num == 1:
# If the element is 1, increment the current streak count.
current_count += 1
else:
# If the element is 0, reset the streak count.
current_count = 0
# After each element, update the maximum streak found so far.
max_count = max(max_count, current_count)
return max_count
Max Consecutive Ones in Java
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxCount = 0;
int currentCount = 0;
for (int num : nums) {
if (num == 1) {
// If we see a 1, increment the current count of consecutive 1s.
currentCount++;
} else {
// If we see a 0, the sequence is broken.
// Reset the current count.
currentCount = 0;
}
// Update the overall maximum count with the current count.
// This ensures we capture the maximum length after each potential sequence.
maxCount = Math.max(maxCount, currentCount);
}
return maxCount;
}
}
Max Consecutive Ones in C++
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxCount = 0;
int currentCount = 0;
for (int num : nums) {
if (num == 1) {
// If the current element is 1, increment the counter for the current window of 1s.
currentCount++;
} else {
// If the current element is 0, it breaks the sequence of 1s.
// Reset the current counter.
currentCount = 0;
}
// Update the maximum count found so far.
// This is done in every iteration to correctly capture the max length.
maxCount = max(maxCount, currentCount);
}
return maxCount;
}
};
Max Consecutive Ones in TypeScript
function findMaxConsecutiveOnes(nums: number[]): number {
let maxCount = 0;
let currentCount = 0;
for (const num of nums) {
if (num === 1) {
// If the current number is 1, increment the count of the current consecutive sequence.
currentCount++;
} else {
// If the current number is 0, the sequence is broken. Reset the counter.
currentCount = 0;
}
// Update the maximum count seen so far. This is done in every iteration
// to ensure we capture the maximum length at any point in the array.
maxCount = Math.max(maxCount, currentCount);
}
return maxCount;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.