Skip to content

Commit 30c0c30

Browse files
committed
Max consecutive ones.
1 parent 33a0857 commit 30c0c30

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
Given a binary array nums, return the maximum number of consecutive 1's in the array.
3+
4+
 
5+
6+
Example 1:
7+
Input: nums = [1,1,0,1,1,1]
8+
Output: 3
9+
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
10+
11+
Example 2:
12+
Input: nums = [1,0,1,1,0,1]
13+
Output: 2
14+
 
15+
16+
Constraints:
17+
- 1 <= nums.length <= 105
18+
- nums[i] is either 0 or 1.
19+
*/
20+
class Solution {
21+
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
22+
var max = 0
23+
var current = 0
24+
for e in nums {
25+
if e == 1 {
26+
current += 1
27+
} else {
28+
if current > max {
29+
max = current
30+
}
31+
current = 0
32+
}
33+
}
34+
return max > current ? max : current
35+
}
36+
}
37+
38+
let s = Solution()
39+
let r = s.findMaxConsecutiveOnes([1,1,0,1,1,0,0,1,0,1,1,1,1])
40+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/485.Max Consecutive Ones.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
92. [Hamming Distance](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/461.Hamming%20Distance.playground/Contents.swift)
9797
93. [Number Complement](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/476.Number%20Complement.playground/Contents.swift)
9898
94. [License Key Formatting](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/482.License%20Key%20Formatting.playground/Contents.swift)
99+
95. [Max Consecutive Ones](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/485.Max%20Consecutive%20Ones.playground/Contents.swift)
99100

100101
#### Medium
101102

0 commit comments

Comments
 (0)