Find Max Consecutive Ones

Problem Link:

https://leetcode.com/problems/max-consecutive-ones/description/

Problem Statement:

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.
        

Approach:? We maintain a variable count that keeps a track of the number of consecutive 1’s while traversing the array. The other variable max_count maintains the maximum number of 1’s, in other words, it maintains the answer.

We start traversing from the beginning of the array. Since we can encounter either a 1 or 0 there can be two situations:-

  1. If? the value at the current index is equal to 1 we increase the value of count by one. After updating? the count variable if it becomes more than the max_count? update the max_count.
  2. If the value at the current index is equal to zero we make the variable count as 0 since there are no more consecutive ones.

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int min=0;
        int maxi=0;
        for (int num : nums) {
            if (num == 1) {
                min++;
            } else {
                min = 0;

            }
            maxi= Math.max(min, maxi);
        }
        return maxi;
    }
}        
Saad Khan

Mobile ApplicationDeveloper | Flutter Developer | Dart

3 个月

Great ??

回复

要查看或添加评论,请登录

Farhan Khattak的更多文章

社区洞察

其他会员也浏览了