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;
    }
};
相关推荐
IT大师兄吖4 分钟前
flux-2-Klein-BFS-换头换脸工作流 懒人整合包
算法·宽度优先
水饺编程9 分钟前
第4章,[标签 Win32] :SysMets3 程序讲解02,iVertPos
c语言·c++·windows·visual studio
波哥学开发12 分钟前
深入解析 BEV 图像色彩调整与伪彩色映射:从直方图统计到着色器实现
算法·图形学
Yungoal20 分钟前
数据结构综合0-排序
数据结构
西西弟21 分钟前
最短路径之Floyd算法(数据结构)
数据结构·算法
小O的算法实验室27 分钟前
2026年SEVC,直觉模糊不确定环境下求解绿色多物品固定费用五维运输问题的多目标进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
SilentSlot29 分钟前
【数据结构】红黑树定义及基本操作
数据结构
海海不瞌睡(捏捏王子)38 分钟前
Unity A*寻路算法
算法·unity
jaysee-sjc42 分钟前
【项目三】用GUI编程实现局域网群聊软件
java·开发语言·算法·安全·intellij-idea
Hello-FPGA44 分钟前
视觉软件工程师(机器视觉 / 科学成像方向)
c++