力扣1658.将x减到0的最小操作数

力扣1658.将x减到0的最小操作数

题目

题目解析及思路

题目要求每次操作删除最左或最右的元素 ,并从x中减去,返回当x = 0 时的最小操作数

  • 正难则反:求值为sum - x的区间

代码

cpp 复制代码
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int res=1e5+10,n = nums.size();
        int sum = accumulate(nums.begin(),nums.end(),0);
        int ans = 0;
        int k = sum - x;
        if(k <0) return -1;
        for(int i=0,j=0;i<n;i++)
        {
            ans += nums[i];
            while(ans > k) ans -= nums[j++];
            if(ans == k) res = min(res,n- (i-j+1));
        }
        if(res == 1e5 + 10) res = -1;
        return res;
    }
};
相关推荐
lsylalalala3 小时前
常见的排序算法1
数据结构·算法·排序算法
想吃火锅10053 小时前
【leetcode】54. 螺旋矩阵
算法·leetcode·矩阵
想吃火锅10054 小时前
【leetcode】300. 最长递增子序列
算法·leetcode·职场和发展
imaol14 小时前
数据结构---队列
java·数据结构·算法
数模竞赛Paid answer4 小时前
2026年电工杯数学建模A题绿电直连型电氢氨园区优化运行求解全过程论文及程序
算法·数学建模·电工杯
疯狂打码的少年4 小时前
【数据结构】串的模式匹配:KMP算法(重点)
数据结构·笔记·算法
Dr.kangder4 小时前
嵌入式面试总结(八)——大小端
嵌入式硬件·面试·职场和发展·架构·嵌入式
晚风醉蝶5 小时前
第零篇-算法全景图
算法
疯狂打码的少年5 小时前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
webmote335 小时前
用 NVIDIA Nemotron 3 Super + .NET 构建有记忆的多轮对话
后端·算法