LeetCode75——Day16

文章目录

一、题目

1004. Max Consecutive Ones III

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

二、题解

滑动窗口+前缀和

cpp 复制代码
class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> P(n + 1);
        for (int i = 1; i <= n; ++i) {
            P[i] = P[i - 1] + (1 - nums[i - 1]);
        }
        int ans = 0;
        for (int right = 0; right < n; ++right) {
            int left = lower_bound(P.begin(), P.end(), P[right + 1] - k) - P.begin();
            ans = max(ans, right - left + 1);
        }
        return ans;
    }
};
相关推荐
liulilittle29 分钟前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
无聊的小坏坏1 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   1 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
山河木马1 小时前
前端学习C++之:.h(.hpp)与.cpp文件
前端·javascript·c++
2401_891957311 小时前
list的一些特性(C++)
开发语言·c++
秋说1 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
qq_513970441 小时前
力扣 hot100 Day37
算法·leetcode
不見星空2 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack2 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
米饭「」2 小时前
C++AVL树
java·开发语言·c++