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

numsi 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;
    }
};
相关推荐
不会就选b1 分钟前
算法日常・每日刷题
算法
一只小小的芙厨8 分钟前
最短路总结
数据结构·算法
致Great14 分钟前
OpenAI 又把 Codex 往前推了一步: 以后做 Agent,没必要都造一个聊天框
算法
脑子不好的小菜鸟1 小时前
秋招、实习 小知识点复习 (C/C++/Linux)—— 碎片时间可看
c++·求职招聘
aqiu1111112 小时前
【算法刷题】蓝桥杯/AtCoder:删除元素后的中位数问题(Symmetry / Median)
算法·蓝桥杯·排序·中位数
charlie1145141912 小时前
深探std::vector:三指针、扩容与迭代器失效
开发语言·c++·开源项目
圣保罗的大教堂2 小时前
leetcode 1386. 安排电影院座位 中等
leetcode
看我眼色行事^ \/ ^2 小时前
2024.05.11 360春招WEB前端编程题
算法
laplaya2 小时前
ROS常用消息之PointCloud2
c++
来一碗刘肉面2 小时前
有向无环图 DAG(描述表达式)
数据结构