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;
    }
};
相关推荐
木木子229 小时前
# 密码强度检测深度解析:正则表达式实时分析、多维度评分算法与可视化反馈
mysql·算法·华为·正则表达式·harmonyos
Sw1zzle12 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空12 小时前
【算法-查找】查找算法
java·数据结构·算法
海石12 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石12 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
殳翰12 小时前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
青瓦梦滋13 小时前
协议定制/序列化-反序列化(Linux视角)
linux·服务器·网络·c++
珠海西格电力16 小时前
云边端协同架构:零碳园区管理系统的技术底座
大数据·运维·人工智能·算法·架构·能源
山登绝顶我为峰 3(^v^)317 小时前
C/C++ 交叉编译方法
java·c语言·c++
还有多久拿退休金17 小时前
让飞书知识库跟着 commit 自己长:一套自动化知识库的真实实现
前端·算法·架构