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;
    }
};
相关推荐
fpcc16 小时前
并行编程实战——CUDA编程的打印输出
c++·cuda
程序leo源16 小时前
Qt信号与槽深度详解
c语言·开发语言·数据库·c++·qt·c#
水云桐程序员16 小时前
C++数组详细介绍
开发语言·c++
z2005093016 小时前
今日算法(二叉树)
数据结构·c++·算法
南境十里·墨染春水16 小时前
八大排序算法 - 基数排序
算法·排序算法
老四啊laosi16 小时前
[滑动窗口] 12. 将 x 减到 0 的最小操作数
算法·leetcode·将 x 减到 0 的最小操作数
一条大祥脚16 小时前
Codeforces Round 1098 (Div. 2)
算法·深度优先
时空自由民.17 小时前
平衡车PID控制系统(豆包版本)
算法
sno_guo17 小时前
直播抠图技术100谈之25---调色中曲线是最优解
人工智能·算法·机器学习·直播·内容运营·obs抠图·直播技术
故事和你9117 小时前
洛谷-【图论2-2】最短路1
开发语言·数据结构·c++·算法·动态规划·图论