알고리즘

[Leetcode]Max Consecutive Ones

JUNGKEUNG 2021. 9. 9. 11:11

https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

Success

이진 배열 숫자가 주어지면 배열에서 연속된 최대 1을 반환한다.

 

풀이

nums[i] 에는 0과 1로 이루어져있다. [1,0,0,1,1,0,1] 이 있다면 연속된 1이 몇개있는지 찾는것이다. [1,0,0,1,1,0,1] 안에는 2개가 있고 만약 [1,1,0,1,1,1] 이 있다면 앞에는 연속된 1이 2개고 뒤에는 3개이다 그럼 1이 가장 많은걸 찾는것이니 3으로 출력이 되게 해야한다.

class Sloution{
	public int findMaxConsectiveOnes(int[] nums){
    
    int count = 0;  //1이 있으면 count가 증가한다.
    int max = 0;    //1이 가장많은 값이 저장된다.
    
   
    for(int n : nums){
		//n이 1이면 count가 증가한다.
    	if(n==1){
        	count++;
            //max가 count보다 작으면 count와 max을 같게해준다.
            if(max < count)
            	max =count;
        }
        //만약 count가 1과 같지않으면 0으로해준다.
        else count = 0;
     }
     return max;
     }
}

다른 풀이

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

 

위에서는 Math.max라는 함수를 사용하여 (maxCount, count) 두 인자 값중 큰값을 리턴 해주고 있다.