[easy] Max Consecutive Ones

문제 : 

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.

 

나의 코드 - 1 (for문을 활용)

var findMaxConsecutiveOnes = function(nums) {    
     
   ** 방법1 (for문 활용)

// 1의 개수 
    let max = 0;
    let count = 0;
    
    //nums 완전 탐색을 통해 1의 개수 찾기
    for(let i = 0; i < nums.length ; i++){
        if(nums[i] === 1){
            count++;
            max = max < count ? count : max;
        }else{
            count = 0;
        }
    }
    return max;
};

 

나의 코드 - 2 (split을 활용)

var findMaxConsecutiveOnes = function(nums) {    
     
    ** 방법2 (split 활용)

    // nums을 string으로 형 변환 
    let str = '';    
    for(num of nums){
        str += num;
    }
    
    // nums를 0으로 split
    let arr = str.split(0);
        
    // 제출할 변수 초기화
    let result = arr[0].length;
    
    // split한 arr 길이 비교
    for(let i = 1; i < arr.length; i++){    
        result = result < arr[i].length ? arr[i].length : result
}
    
    return result;
};

 

여러 방면에서 코드를 시도해볼 수 있는 문제였다.

 

'leetCode > Array 101' 카테고리의 다른 글

[easy] Find Numbers with Even Number of Digits  (0) 2022.05.02