###### tags: `阿瑜` # Day 7: LeetCode 485. Max Consecutive Ones ## Tag:隨意刷-每月挑戰(2021.09.21) ### Source: [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) ### 1.題意: 如題目: 回傳**最長**連續的1 In: binary array `nums` Out: the **maximum** number of consecutive `1`'s in the array ### 2.思路: - 遍歷nums - 遇1則tmpLen++且更新最大連續1長度(maxLen) - 遇0則tmpLen歸零 ### 3.程式碼: #### Python3 ```python= class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: maxLen = 0 tmpLen = 0 for i in nums: if i == 1: tmpLen+=1 maxLen=max(maxLen,tmpLen) else: tmpLen=0 return maxLen ``` #### Java ```java= class Solution { public int findMaxConsecutiveOnes(int[] nums) { int tmpLen = 0; int maxLen = 0; for(int i=0;i<nums.length;i++) { if(nums[i]==1) { tmpLen++; maxLen=Math.max(tmpLen,maxLen); } else { tmpLen=0; } } return maxLen; } } ``` #### Result: ![](https://i.imgur.com/Rqph9LO.png) #### Level:`Easy`