[Java] LeetCode 485. Max Consecutive Ones

Sommi·2023년 8월 1일
0

Algorithm

목록 보기
1/5

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

문제

Given a binary array nums, return the maximum number of consecutive 1's in the array.
연속된 1의 최대 개수를 리턴

소스코드

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int cnt = 0;
        int max = 0;
        
        for(int i : nums){
            if(i == 1){
                cnt++;
                if(cnt > max){
                    max = cnt;
                }
            } else {
                cnt = 0;
            }
        }
        return max;
    }
}

설명

1이 나오면 cnt의 개수를 올리고, 0이 나오면 cnt를 0으로 초기화
max에 cnt의 최대값을 넣고 리턴

profile
넌 할 수 있어 라고 말해 주세요~

0개의 댓글

관련 채용 정보