485. Max Consecutive Ones LeetCode Solution

In this guide, you will get 485. Max Consecutive Ones LeetCode Solution with the best time and space complexity. The solution to Max Consecutive Ones problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Max Consecutive Ones solution in C++
  4. Max Consecutive Ones solution in Java
  5. Max Consecutive Ones solution in Python
  6. Additional Resources
485. Max Consecutive Ones LeetCode Solution image

Problem Statement of Max Consecutive Ones

Given a binary array nums, return the maximum number of consecutive 1’s in the array.

Example 1:

Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

485. Max Consecutive Ones LeetCode Solution in C++

class Solution {
 public:
  int findMaxConsecutiveOnes(vector<int>& nums) {
    int ans = 0;
    int sum = 0;

    for (const int num : nums)
      if (num == 1)
        ans = max(ans, ++sum);
      else
        sum = 0;

    return ans;
  }
};
/* code provided by PROGIEZ */

485. Max Consecutive Ones LeetCode Solution in Java

class Solution {
  public int findMaxConsecutiveOnes(int[] nums) {
    int ans = 0;
    int sum = 0;

    for (final int num : nums)
      if (num == 1)
        ans = Math.max(ans, ++sum);
      else
        sum = 0;

    return ans;
  }
}
// code provided by PROGIEZ

485. Max Consecutive Ones LeetCode Solution in Python

class Solution:
  def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
    ans = 0
    summ = 0

    for num in nums:
      if num == 0:
        summ = 0
      else:
        summ += num
        ans = max(ans, summ)

    return ans
# code by PROGIEZ

Additional Resources

See also  880. Decoded String at Index LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.