Neunomizuの日記

俺だけが俺だけじゃない

# LeetCode Easy 485. Max Consecutive Ones

tags: leetcode

問題

イデア

「バイナリの配列が与えられたとき,最長の1の列を探して長さを返せ」という問題です.

解法

最大の長さと現在連続している長さの2つを保持して解きます.

計算量

配列の長さを$N$とします.

  • 時間計算量
    • $O(N)$
  • 空間計算量
    • $O(1)$

Python

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        max_len = 0
        cur_len = 0
        for num in nums:
            if num == 0:
                max_len, cur_len = max(max_len, cur_len), 0
            else:
                cur_len += 1
                
        return max(max_len, cur_len)