Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 1.93 KB

풀이_LC485.md

File metadata and controls

37 lines (29 loc) · 1.93 KB

🌂 LeetCode 459. Repeated Substring Pattern

  • Date : 2021.09.26(일)
  • Time : 20분

Problem

  • Given a binary array nums, return the maximum number of consecutive 1's in the array.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.

Example

  • 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.

풀이

    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        answer = 0
        continueTime = 0
        nums.append(0)
        for k in nums:
            if k == 1:
                continueTime += 1
            else:
                answer = max(answer, continueTime)
                continueTime = 0
        return answer
        

: 이 문제는 주어진 배열에서 숫자 1이 연속될 때 최대로 연속되는 갯수를 구하는 문제이다. 그렇기 때문에 answer과 continueTime 변수를 생성해 주었는데, answer은 정답을 넣는 변수이고 continueTime 변수는 1이라는 숫자가 시작되고 얼마나 연속되는지를 넣어두는 변수이다. num.append(0)을 한 이유는 마지막에 설명하겠다. 그리고 for문을 통해 배열을 돌았는데 만약에 값이 1이라면 continueTime += 1을 통해 연속되고 있다는 것을 나타내주었다. 만약 0을 만난다면 현재 continueTime 과 answer 중에 더 큰 숫자를 answer로 다시 지정해준후 continueTime을 다시 0으로 초기화 시켜주는 과정이 필요하다. 이제 왜 앞에서 nums에 0을 마지막에 넣었는지가 나오는데, 만약에 0을 마지막에 넣지 않았을 때 1로 배열이 끝나게 된다면 for문을 끝냈을 때 다시 한번 answer, continueTime 의 최대값을 비교하는 과정을 추가해줘야한다. 이런 불편함을 줄이기 위해 제일 마지막에 0을 삽입해 끝났다는 의미를 더해준 것이다.