E. Binary Deque[双指针好思维题]

Binary Deque

题面翻译

有多组数据。

每组数据给出 n n n 个数,每个数为 0 0 0 或 1 1 1 。你可以选择从两边删数,求至少删几个数才可以使剩下的数总和为 s s s 。

如果不能达到 s s s ,则输出 − 1 -1 −1 。

题目描述

Slavic has an array of length n consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array.

What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to s after performing all the operations? In case the sum s can't be obtained after any amount of operations, you should output -1.

样例 #1

样例输入 #1

复制代码
7
3 1
1 0 0
3 1
1 1 0
9 3
0 1 0 1 1 1 0 0 1
6 4
1 1 1 1 1 1
5 1
0 0 1 1 0
16 2
1 1 0 0 1 0 0 1 1 0 0 0 0 0 1 1
6 3
1 0 1 0 0 0

样例输出 #1

复制代码
0
1
3
2
2
7
-1
cpp 复制代码
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int t, n, m;
int w[2000005];
int main()
{
    cin >> t;
    while (t--)
    {
        int num1 = 0, num2 = 0, temp = 0,sum=0;
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            cin >> w[i],sum += w[i];
        if (sum < m){//特判
            cout << -1 << endl;结束
            continue;
        }
        int num = 0;
        int ans = 0;
        for (int i = 1, j = 1; i <= n;i++) {
            num += w[i];
            while (j<i && num>m){
            //双指针前后符合并且和太大了就做减法
                num -= w[j++];//减去
            }
            if (num == m){
                ans = max(ans, i - j + 1);//不断更新
            }
        }
        cout <<n-ans << endl;
    }
    return 0;
}
相关推荐
2301_78877055几秒前
OJ模拟2
数据结构·算法
Q741_1476 分钟前
每日一题 力扣 3548. 等和矩阵分割 II 前缀和 哈希表 C++ 题解
算法·leetcode·前缀和·矩阵·力扣·哈希表
木井巳8 分钟前
【递归算法】全排列 Ⅱ
java·算法·leetcode·决策树·深度优先·剪枝
Fcy6489 分钟前
算法竞赛有关数据结构的补充(3)—— 二叉树、堆和哈希表的静态实现(包括红黑树和AVL树动态实现)
数据结构·算法·散列表
代码探秘者9 分钟前
【算法篇】6.分治
java·数据结构·后端·python·算法·排序算法
TechPioneer_lp12 分钟前
2026微软SDE LeetCode高频题:208道,按频度排序,含备考建议
算法·leetcode·microsoft·leetcode刷题·大厂算法刷题·微软sde·微软笔试题
科德航空的张先生13 分钟前
空管模拟器在塔台指挥训练中的应用与效能分析
人工智能·算法
勤劳的进取家16 分钟前
Excel 公式使用手册(精简)
算法·excel
xiaoye-duck17 分钟前
《算法题讲解指南:优选算法-哈希表》--56.两数之和,57.判断是否互为字符重排
c++·算法·哈希表
米粒124 分钟前
力扣算法刷题 Day23
数据库·算法·leetcode