[LeetCode] Max Consecutive Ones

rush0wj·2024년 8월 5일

Leetcode

목록 보기
1/6

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. 최대 연속의수

  2. 배열에 담겨있어 for문을 length만큼 돌린후 if문을 통해
    nums[i]가 1일 경우 count를 더해주고,아닐경우 0으로 초기화

  3. Math.max(a, b) - a, b 중에 큰 값을 사용

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        
        
        int count = 0;
        int max = 0;
        
        for(int i = 0; i < nums.length; i++){
        
            if(nums[i] == 1){
                count++;
            }else{
                count = 0;
            }
            
            max = max > count ? max : count;
            // System.out.println(max);

        }
        
        return max;
    }
}
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        
        int count = 0;
        int max = 0;
        for(int i : nums){
            System.out.println(i);
            if(i == 1){
                count++;
            }else{
                count = 0;
            }
            max = max > count ? max : count;
        }
        
        return  max;
    }
        
}
profile
Developer Record

0개의 댓글