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;
    }
};
相关推荐
承渊政道1 分钟前
【优选算法】(实战掌握分治思想的使用方法)
数据结构·c++·笔记·vscode·学习·算法·leetcode
adam_life5 分钟前
A*算法——# P1379 八数码难题
算法·优先队列·a星算法·最优启发式搜索·哈希标记·启发式函数·已走步数+预估距离
南境十里·墨染春水5 分钟前
C++传记 this指针 及区分静态非静态成员(面向对象)
开发语言·jvm·c++·笔记
揽月凡尘5 分钟前
基于 SWIG 的 C++ Embind 绑定自动化技术说明
开发语言·c++·自动化
Yungoal6 分钟前
C++基础项目结构
数据结构·c++·算法
扶摇接北海17612 分钟前
洛谷:B4477 [语言月赛 202601] 考场安排
数据结构·c++·算法
IAUTOMOBILE14 分钟前
Qt 入门级开发实践:浅析基于 QTtest 项目的 C++ GUI 编程基础
开发语言·c++·qt
爱丽_18 分钟前
AQS 的 `state`:volatile + CAS 如何撑起原子性与可见性
java·前端·算法
2301_7887705519 分钟前
OJ模拟5
数据结构·算法
羊小猪~~22 分钟前
算法/力扣--字符串经典题目
c++·考研·算法·leetcode·职场和发展·哈希算法