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;
    }
};
相关推荐
问商十三载3 小时前
2026法律行业AI引擎生成式优化怎么优化?三层专业加固提排名,零成本提33%引用率附适配表
java·前端·人工智能·算法
野生风长3 小时前
c++类和对象(this指针,重载operator,习题总结)
java·开发语言·c++
雪的季节3 小时前
Python「假多态」与 C++「真多态」的核心区别
开发语言·c++
zander2583 小时前
138. 随机链表的复制
数据结构·算法·链表
过期动态3 小时前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
来一碗刘肉面3 小时前
栈在递归中的应用
数据结构·算法
8K超高清3 小时前
博冠获中国电影电视技术学会科技进步奖
人工智能·科技·算法·安全·接口隔离原则·智能硬件
皓月斯语3 小时前
程序设计语言的特点
开发语言·数据结构·c++
微石科技4 小时前
长期慢病如何做好居家管理?宁波微石科技星梦云康改善周期数据零散短板
大数据·科技·物联网·算法