Skip to content

Commit 127a071

Browse files
committed
1004 solved.
1 parent 0bfb0cf commit 127a071

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
cmake_minimum_required(VERSION 3.13)
2+
project(C)
3+
4+
set(CMAKE_CXX_STANDARD 14)
5+
6+
add_executable(C main.cpp)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/// Source : https://leetcode.com/problems/max-consecutive-ones-iii/
2+
/// Author : liuyubobobo
3+
/// Time : 2019-03-02
4+
5+
#include <iostream>
6+
#include <vector>
7+
8+
using namespace std;
9+
10+
11+
/// Sliding Window
12+
/// Time Complexity: O(n)
13+
/// Space Complexity: O(1)
14+
class Solution {
15+
public:
16+
int longestOnes(vector<int>& A, int K) {
17+
18+
int i = 0, j = -1, curK = 0, curLen = 0, best = 0;
19+
while(j + 1 < A.size()){
20+
if(A[j + 1] == 1)
21+
curLen += 1,
22+
j ++;
23+
else{
24+
// data[j + 1].first == 0
25+
if(curK < K)
26+
curLen += 1,
27+
curK += 1,
28+
j ++;
29+
else
30+
curLen -= 1,
31+
curK -= (A[i] == 0 ? 1 : 0),
32+
i ++;
33+
}
34+
best = max(best, curLen);
35+
}
36+
return best;
37+
}
38+
};
39+
40+
41+
int main() {
42+
43+
vector<int> A1 = {1,1,1,0,0,0,1,1,1,1,0};
44+
cout << Solution().longestOnes(A1, 2) << endl;
45+
// 6
46+
47+
vector<int> A2 = {0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1};
48+
cout << Solution().longestOnes(A2, 3) << endl;
49+
// 10
50+
51+
vector<int> A3 = {1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,0,0,1,1,0,1,1};
52+
cout << Solution().longestOnes(A3, 8) << endl;
53+
// 25
54+
55+
return 0;
56+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,4 +668,5 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
668668
| | | | | | |
669669
| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters/) | [] | [C++](1002-Find-Common-Characters/cpp-1002/) | | |
670670
| 1003 | [Check If Word Is Valid After Substitutions](https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/) | [] | [C++](1003-Check-If-Word-Is-Valid-After-Substitutions/cpp-1003/) | | |
671+
| 1004 | [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) | [] | [C++](1004-Max-Consecutive-Ones-III/cpp-1004/) | | |
671672
| | | | | | |

0 commit comments

Comments
 (0)