LeetCode 485: Max Consecutive Ones Solution

Master LeetCode problem 485 (Max Consecutive Ones), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

485. Max Consecutive Ones

Easy

Problem Explanation

Explanation

To solve this problem, we can iterate through the binary array nums and keep track of the current consecutive count of 1s. We update the maximum consecutive count whenever we encounter a 0 or reach the end of the array. Finally, we return the maximum consecutive count.

  • Algorithm:

    1. Initialize variables maxConsecutive and currentConsecutive to 0.
    2. Iterate through the array nums:
      • If the current element is 1, increment currentConsecutive.
      • If the current element is 0, update maxConsecutive if currentConsecutive is greater and reset currentConsecutive to 0.
    3. Update maxConsecutive with the final currentConsecutive.
    4. Return maxConsecutive.
  • Time Complexity: O(n), where n is the length of the binary array.

  • Space Complexity: O(1)

Solution Code

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int maxConsecutive = 0;
        int currentConsecutive = 0;
        
        for (int num : nums) {
            if (num == 1) {
                currentConsecutive++;
            } else {
                maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
                currentConsecutive = 0;
            }
        }
        
        maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
        
        return maxConsecutive;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 485 (Max Consecutive Ones)?

This page provides optimized solutions for LeetCode problem 485 (Max Consecutive Ones) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 485 (Max Consecutive Ones)?

The time complexity for LeetCode 485 (Max Consecutive Ones) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 485 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 485 in Java, C++, or Python.

Back to LeetCode Solutions