485. Max Consecutive Ones

inhalin·2021년 2월 17일
0

Leetcode Easy

목록 보기
1/14

문제

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

1, 0으로 이루어진 배열에서 연속으로 1이 나오는 제일 큰 수 찾기

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 input array is a positive integer and will not exceed 10,000

Solution

배열을 돌면서 1이 나오면 count에 1씩 더해주고 0이면 count를 0으로 초기화한다. maxNum과 count에서 큰 수를 maxNum에 저장해준다.

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int maxNum = 0;
        int counter = 0;
        
        for(int i = 0; i < nums.length; i++){
            if(nums[i]==1){
                counter++;
                maxNum = Math.max(maxNum, counter);
            } else{
                counter = 0;
            }
        }
        
        return maxNum;
    }
}

0개의 댓글