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;
    }
};
相关推荐
m沐沐6 小时前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b6 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu7 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
Zachery Pole9 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米9 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035779 小时前
【算法】最长递增子序列(三种解法)
算法
hold?fish:palm10 小时前
kv存储主从复制的设计与实现
c++·redis·后端
啦啦啦啦啦zzzz10 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
charlie11451419110 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
清泓y12 小时前
RAG 技术
算法·ai