LeetCode 0485. Max Consecutive Ones Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0485. Max Consecutive Ones

Description

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.

Solutions

Solution 1: Single Pass

We can iterate through the array, using a variable cnt to record the current number of consecutive 1s, and another variable ans to record the maximum number of consecutive 1s.

When we encounter a 1, we increment cnt by one, and then update ans to be the maximum of cnt and ans itself, i.e., ans = max(ans, cnt). Otherwise, we reset cnt to 0.

After the iteration ends, we return the value of ans.

The time complexity is O(n), where n is the length of the array. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptPHP
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: ans = cnt = 0 for x in nums: if x: cnt += 1 ans = max(ans, cnt) else: cnt = 0 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !