-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathMaxConsecutiveOnes.swift
More file actions
32 lines (27 loc) · 908 Bytes
/
MaxConsecutiveOnes.swift
File metadata and controls
32 lines (27 loc) · 908 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Question Link: https://leetcode.com/problems/max-consecutive-ones/
* Primary idea: Iterate the whole array and summarize consective ones locally and update globally encountering 0
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class MaxConsecutiveOnes {
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
// Output
var maximumConsecutiveSum = 0
guard !nums.isEmpty else {
return maximumConsecutiveSum
}
var currentRunningSum = 0
for eachNumber in nums {
if eachNumber == 1 {
currentRunningSum += 1
} else {
currentRunningSum = 0
}
if currentRunningSum > maximumConsecutiveSum {
maximumConsecutiveSum = currentRunningSum
}
}
return maximumConsecutiveSum
}
}