[leetcode #485] Max Consecutive Ones

Seongyeol Shin·2021년 12월 1일
0

leetcode

목록 보기
93/196
post-thumbnail

Problem

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.

Idea

너무나 쉬운 문제다. 9월 문제인데 안 풀고 있다가 Redeem이 남아서 이제야 풀게 되었다.

nums array를 탐색하다가 1이 나오면 current값을 increment시키고 다음 element로 넘어간다. 0이 나올 경우 현재 res값과 current값 중 더 큰 값을 res값으로 치환하고, current값은 0으로 초기화한다.

마지막에 res와 current 중 더 큰 값을 리턴하면 된다.

Solution

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int res = 0;
        int current = 0;

        for (int i=0; i < nums.length; i++) {
            if (nums[i] == 1) {
                current++;
                continue;
            }
            res = Math.max(res, current);
            current = 0;
        }

        return Math.max(res, current);
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글