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;
    }
};
相关推荐
fie88893 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法
晨晖23 小时前
单链表逆转,c语言
c语言·数据结构·算法
kk哥88994 小时前
C++ 对象 核心介绍
java·jvm·c++
helloworddm4 小时前
WinUI3 主线程不要执行耗时操作的原因
c++
YoungHong19924 小时前
面试经典150题[072]:从前序与中序遍历序列构造二叉树(LeetCode 105)
leetcode·面试·职场和发展
无能者狂怒5 小时前
YOLO C++ Onnx Opencv项目配置指南
c++·opencv·yolo
im_AMBER5 小时前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
集智飞行5 小时前
c++函数传参的几种推荐方式
开发语言·c++
鼾声鼾语5 小时前
matlab的ros2发布的消息,局域网内其他设备收不到情况吗?但是matlab可以订阅其他局域网的ros2发布的消息(问题总结)
开发语言·人工智能·深度学习·算法·matlab·isaaclab
LYFlied6 小时前
【每日算法】LeetCode 25. K 个一组翻转链表
算法·leetcode·链表