Day23力扣打卡

打卡记录

将 x 减到 0 的最小操作数(逆向思维 + 滑动窗口)

链接

将 x 减到 0 的最小操作数,可以逆向思考,求一个数组中的最大长度的滑动窗口,来使得这个窗口里的数等于 全数组之和 - x 的值。

cpp 复制代码
class Solution {
public:
    int minOperations(vector<int> &nums, int x) {
        int target = accumulate(nums.begin(), nums.end(), 0) - x;
        if (target < 0) return -1;
        int ans = -1, sum = 0, n = nums.size();
        for (int i = 0, j = 0; i < n; ++i) {
            sum += nums[i];
            while (sum > target) sum -= nums[j++];
            if (sum == target) ans = max(ans, i - j + 1);
        }
        return ans < 0 ? -1 : n - ans;
    }
};
相关推荐
Xの哲學4 分钟前
Linux 分区表深度技术剖析
linux·网络·算法·架构·边缘计算
写写闲篇儿12 分钟前
经典算法题剖析之传递信息(三)
算法
上不如老下不如小13 分钟前
2025年第七届全国高校计算机能力挑战赛初赛 Python组 编程题汇总
开发语言·python·算法
xlq2232232 分钟前
19.模版进阶(上)
c++
yuuki23323335 分钟前
【C++】初识C++基础
c语言·c++·后端
小年糕是糕手35 分钟前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
玫瑰花店1 小时前
SomeIP报文详解
c++·someip
kupeThinkPoem1 小时前
跳表有哪些算法?
数据结构·算法
利刃大大1 小时前
【c++中间件】redis介绍 && redis-plus-plus库使用
c++·redis·中间件
前端小L1 小时前
图论专题(二十一):并查集的“工程应用”——拔线重连,修复「连通网络」
数据结构·算法·深度优先·图论·宽度优先