Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does leetcode calculate the number of maximum consecutive ones

Shulou Source: shulou.com Published: 2022-06-01 13:21:32 09月12日 Update

This article mainly introduces how leetcode calculates the number of maximum consecutive 1s, which is very detailed and has a certain reference value. Friends who are interested must read it!

I. the content of the topic

Given a binary array, calculate the number of maximum consecutive ones in it.

Example:

Input: [1pyrum 1pcr0pl 1p1p1pl]

Output: 3

Explanation: the first two digits and the last three digits are consecutive ones, so the maximum number of consecutive ones is 3.

Tip:

The array entered contains only 0 and 1.

The length of the input array is a positive integer and does not exceed 10000.

Second, the way to solve the problem

1. Record the length directly and then compare the size each time.

two。 Slide the window, increase the window length each time until it is 0, record the length and compare the current maximum length, and then start recording the length again from where it is 1, so you can compare it over and over again.

Code class Solution: def findMaxConsecutiveOnes1 (self, nums: list)-> int: count = 0 ans = 0 for num in nums: if num = = 1: count + = 1 ans = max (ans, count) else: count = 0 return ans def findMaxConsecutiveOnes2 (self, nums: list)-> int: left, right = 0 0 ans = 0 while right < len (nums): if nums [right] = = 1: right + = 1 else: ans = max (ans, right-left) right + = 1 left = right ans = max (ans Right-left) return ansif _ _ name__ ='_ _ main__': s = Solution () nums = [1, 1, 0, 1, 1, 1] ans1 = s.findMaxConsecutiveOnes1 (nums) print (ans1) ans2 = s.findMaxConsecutiveOnes2 (nums) print (ans2) all the contents of the article "how leetcode calculates the maximum number of consecutive ones" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Length maximum number content array input article binary code value interest place size boy buddy beginning idea integer more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MySQL Shulou Tech Info Xiaomi NVidia