forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1004. Max Consecutive Ones III.cpp
89 lines (53 loc) · 1.69 KB
/
1004. Max Consecutive Ones III.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Given a binary array nums and an integer k,
return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
0 <= k <= nums.length
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
int start = 0, end = 0, res = 0;
while (end < nums.size()) {
if (nums[end] == 0 && k > 0) {
k--;
} else if (nums[end] == 0 && k == 0){
while (nums[start] != 0) start++;
start++; // to next element
}
res = max(res, end - start + 1);
end++;
}
return res;
}
};
// can be done without ones variable
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
int start = 0, end = 0, res = 0, ones = 0;
while (end < nums.size()) {
if (nums[end] == 1) ones++;
else if (nums[end] == 0 && k > 0) {
ones++;
k--;
} else {
while (nums[start] != 0) start++;
start++; // to next element
}
res = max(res, end - start + 1);
end++;
}
return res;
}
};