Line data Source code
1 : // Copyright (c) 2022 The Authors. All rights reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : // Authors: liubang (it.liubang@gmail.com)
16 : // Created: 2022/01/17 14:50
17 :
18 : #include <gtest/gtest.h>
19 :
20 : #include <vector>
21 :
22 : namespace {
23 : class Solution {
24 : public:
25 2 : int findMaxConsecutiveOnes(std::vector<int>& nums) {
26 2 : int ret = 0, cur = 0;
27 14 : for (auto num : nums) {
28 12 : if (num == 0) {
29 3 : ret = std::max(ret, cur);
30 3 : cur = 0;
31 : } else {
32 9 : cur++;
33 : }
34 : }
35 2 : return std::max(ret, cur);
36 : }
37 : };
38 : } // namespace
39 :
40 4 : TEST(Leetcode, max_consecutive_ones) {
41 1 : Solution s;
42 : {
43 1 : std::vector<int> nums = {1, 1, 0, 1, 1, 1};
44 1 : auto res = s.findMaxConsecutiveOnes(nums);
45 1 : EXPECT_EQ(3, res);
46 1 : }
47 : {
48 1 : std::vector<int> nums = {1, 0, 1, 1, 0, 1};
49 1 : auto res = s.findMaxConsecutiveOnes(nums);
50 1 : EXPECT_EQ(2, res);
51 1 : }
52 1 : }
|