Description:
https://leetcode.com/problems/max-consecutive-ones/description/
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int count = 0; int maxCount = 0; for (int i = 0; i < nums.size();i++) { if (nums[i] == 1) { count++; maxCount = count > maxCount ? count : maxCount; } else count = 0; } return maxCount; } }; |
Time & Space:
O(n) & O(1)
Refactored:
class Solution {
public:
int findMaxConsecutiveOnes(vector& nums) {
int ans = 0, cur = 0;
for (const auto x : nums) {
if (x == 1) {
if (++cur > ans) ans = cur;
} else {
cur = 0;
}
}
return ans;
}
};