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;
    }
};
相关推荐
HjhIron17 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩18 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹20 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn2 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法