Skip to content

Instantly share code, notes, and snippets.

@aniltv06
Created February 28, 2021 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniltv06/21b60ad61e7dc5820dd686bc31fa3bcc to your computer and use it in GitHub Desktop.
Save aniltv06/21b60ad61e7dc5820dd686bc31fa3bcc to your computer and use it in GitHub Desktop.
Max Consecutive Ones
/*
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