Max Consecutive Ones Solution

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

Approach
To solve this problem we can iterate through the indices in the array in two nested while loop by following algorithm:

  1. Create a variable maximum which will store the updated maximum consecutive 1s during traversing.
  2. Create and initialize a variable i with first index.
  3. Now run a while loop until i < array size.
  4. Inside the loop we will check if number at current index i is 1 or not. If it is not equal to 1 then simply increment the index i. Else if it is equal to 1, then run a nested while loop by creating a count variable and initialize with 0. Then traverse the array for consecutive 1s in that nested while loop. i.e. traverse array while num[i] is equal to 1, along with keep incrementing the count of current consecutive 1s as shown in figure below:
    在这里插入图片描述
  5. After encountering 0 or end of the array, update the maximum variable by comparing its old value with current consecutive 1s count stored in count variable.
  6. After while loop completes return the maximum value.
int findMaxConsecutiveOnes(int* nums, int numsSize){

    int maximum=0;
    int i=0;
    
    while(i<numsSize){
        int conOnes=0;
        while(i<numsSize&&nums[i]==1){
            conOnes++;
            i++;
        }
        if(conOnes>maximum){
            maximum=conOnes;
        }
        i++;
    }
    
    return maximum;
}
int findMaxConsecutiveOnes(int* nums, int numsSize){

    int maximum=0;
    int i=0;
    int conOnes=0;
    
    while(i<numsSize){
        
        if(nums[i]!=0){
            conOnes++;
            i++;
        }
        else{
            conOnes=0;
            i++;
        }
            
        if(conOnes>maximum)
            maximum=conOnes;
        
    }
    
    return maximum;
}

来源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值