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;
    }
};
相关推荐
ZHW_AI课题组19 小时前
基于逻辑回归的乳腺癌预测分类
算法·分类·逻辑回归
Ricky_Theseus19 小时前
B树和B+树的区别
数据结构·b树
胡志辉19 小时前
贪心算法最坑的地方:每一步都看起来很对,最后还是错了
算法
Hua-Jay19 小时前
OpenCV联合C++/Qt 学习笔记(二十)----Harri角点检测、Shi-Tomas角点检测及亚像素级别角点位置优化
c++·笔记·qt·opencv·学习·计算机视觉
代码北人生20 小时前
GitHub 日榜第一、月下载 110 万:supervision 出现之前,写计算机视觉代码是什么感觉
算法·claude
南宫萧幕20 小时前
HEV能量管理策略 Simulink 实战:从零搭建 Rule-based 与 A-ECMS 对比模型及排错指南
人工智能·算法·matlab·simulink·控制
萧戈20 小时前
C/C++ 运行时库概念详解
c语言·c++
十五年专注C++开发20 小时前
QFluentKit: 一个基于 Qt Widgets 的 Fluent Design 风格 UI 组件库
开发语言·c++·qt·ui·qfluentkit
Hua-Jay20 小时前
OpenCV联合C++/Qt 学习笔记(十九)----图像分割
c++·笔记·qt·opencv·学习
kyle~20 小时前
调试器---GDB(Linux/Unix平台下编译型语言,C++、Go、Rust)
linux·c++·unix