Created
February 28, 2021 21:57
-
-
Save aniltv06/21b60ad61e7dc5820dd686bc31fa3bcc to your computer and use it in GitHub Desktop.
Max Consecutive Ones
This file contains 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
/* | |
Given a binary array, find the maximum number of consecutive 1s in this array. | |
Example 1: | |
Input: [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. | |
Note: | |
The input array will only contain 0 and 1. | |
The length of input array is a positive integer and will not exceed 10,000 | |
*/ | |
class Solution { | |
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { | |
var maxCount = 0 | |
var consecutive1s = 0 | |
for sub in stride(from: 0, to: nums.count, by: 1) { | |
if nums[sub] == 1 { | |
consecutive1s += 1 | |
} else { | |
maxCount = (consecutive1s > maxCount) ? consecutive1s : maxCount | |
consecutive1s = 0 | |
} | |
} | |
return (consecutive1s > maxCount) ? consecutive1s : maxCount | |
} | |
} | |
print(Solution().findMaxConsecutiveOnes([1,1,0,1,1,1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment