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;
    }
};
相关推荐
hanlin032 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
一拳一个呆瓜2 小时前
【STL】文件系统导航
c++·stl
All for pursuit.3 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
栈帧之外3 小时前
【C++】STL之set
开发语言·c++
zhanghaha13144 小时前
C++构造函数的一些其他应用(逐词逐句保姆讲解)
c++
jimy15 小时前
c++的 Type Traits (二、更详细版本)
开发语言·c++
碧海银沙音频科技研究院5 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI5 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo6235 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y6 小时前
DAY2 滑动窗口
算法·leetcode·散列表