민여위-

[Leetcode] Max Consecutive Ones Solution (Explore Arrays 101) / 릿코드 활용, 코딩테스트 본문

Tech

[Leetcode] Max Consecutive Ones Solution (Explore Arrays 101) / 릿코드 활용, 코딩테스트

꿀땡이 2021. 10. 9. 22:06
728x90
반응형

1. 문제설명

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.

2. 내 풀이

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int nCountConsecutiveNum = 0;
        int nMaxConsecutiveNum = 0;
        
        for(int i = 0; i < nums.size(); i++) {
            if(1 == nums[i]) {
                nCountConsecutiveNum ++;
                if(nMaxConsecutiveNum < nCountConsecutiveNum) {
                    nMaxConsecutiveNum = nCountConsecutiveNum;
                }
            } else {
                nCountConsecutiveNum = 0;
            }
        }
        
        return nMaxConsecutiveNum;
    }
};
728x90
반응형
Comments