[파이썬][Leetcode][릿코드] max consecutive ones
1. 문제Permalink
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 either0
or1
.
출처: Leetcode, https://leetcode.com/
2. 해결방법 시간복잡도Permalink
- 단순 코딩 O(N)
3. 문제 해결 및 코드Permalink
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def findMaxConsecutiveOnes(self, nums: List[int]) -> int: | |
cnt = 0 | |
mx = 0 | |
for i in range(len(nums)): | |
if nums[i] == 1: | |
# 반복문이 도는 동안 1을 만나면 | |
cnt += 1 # 갯수를 세준다. | |
if mx < cnt: # 만약 최대 중복 갯수값보다 크다면 | |
mx = cnt # 덮어주기 | |
else: # 만약 중복이 안된다면 | |
cnt = 0 | |
return mx |
-
주석을 참고하면서 이해를 돕습니다.Permalink
4. 알고리즘 및 해설Permalink
- 반복문을 통해 해당 값이 1이라면 카운트해준다.
- 이때 만약 최대 중복 갯수값보다 크다면 그 값을 변경해준다.
- 만약 중복값이 없고, 해당 값이 0이 아니라면 카운트는 0이 된다.
- 최종 덮어준 값을 출력해준다.