Max Consecutive Ones - Array - Easy - LeetCode
💻 coding

Max Consecutive Ones - Array - Easy - LeetCode

1 min read 114 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding the maximum number of consecutive 1s in a binary array.
  • 2The provided solution uses a linear scan with O(n) time complexity and O(1) space complexity.
  • 3An example input of [1,1,0,1,1,1] yields a maximum of 3 consecutive 1s.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding the maximum number of consecutive 1s in a binary array."

Max Consecutive Ones - Array - Easy - LeetCode

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1: Input: [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. Note:

The input array will only contain 0 and 1. The length of the input array is a positive integer and will not exceed 10,000

public class Solution {
 public int FindMaxConsecutiveOnes(int[] nums) {
 int max = 0;
 int curr = 0;
 for(int i=0;i<nums.Length;i++){
 if(nums[i]==0){
 if(curr>max){
 max = curr; 
 }
 curr = 0;
 }
 else{
 curr++;
 }
 }
 
 if(curr>max){
 max = curr;
 }
 
 return max;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 26 September 2020 · 1 min read · 114 words

Part of AskGif Blog · coding

You might also like

Max Consecutive Ones - Array - Easy - LeetCode | AskGif Blog