Problem:1658. 将 x 减到 0 的最小操作数
思路:逆向思维+滑动窗口
Accode:
class Solution {
public:
int minOperations(vector<int>& nums, int x) {
int len = nums.size();
deque<int> deq;
long long tot = 0;
long long sum = 0;
int ans = 0x3f3f3f3f;
for(auto i:nums){
tot+=i;
}
for(int i=0;i<len;i++){
deq.push_back(nums[i]);
sum+=nums[i];
while(deq.size() && tot-sum<x){
sum-=deq.front();
deq.pop_front();
}
if(tot-sum==x) ans = min(ans,(int)(len-deq.size()));
}
return ans==0x3f3f3f3f?-1:ans;
}
};
时间复杂度:$o(n)$