---
# System prepended metadata

title: LC 1004. Max Consecutive Ones III
tags: [medium, leedcode, Sliding Window, python, c++]

---

# LC 1004. Max Consecutive Ones III

### [Problem link](https://leetcode.com/problems/max-consecutive-ones-iii/)

###### tags: `leedcode` `medium` `python` `c++` `Sliding Window`

Given a binary array <code>nums</code> and an integer <code>k</code>, return the maximum number of consecutive <code>1</code>'s in the array if you can flip at most <code>k</code> <code>0</code>'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:** 

- <code>1 <= nums.length <= 10<sup>5</sup></code>
- <code>nums[i]</code> is either <code>0</code> or <code>1</code>.
- <code>0 <= k <= nums.length</code>

## Solution 1 - Sliding Window
#### C++
```cpp=
class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        int cnt0 = 0;
        int ans = 0;
        int l = 0;
        for (int r = 0; r < nums.size(); r++) {
            cnt0 += nums[r] == 0;
            while (cnt0 > k) {
                cnt0 -= nums[l] == 0;
                l++;
            }
            ans = max(ans, r - l + 1);
        }
        return ans;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(1)             |

## Note
x
