Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1658. Minimum Operations to Reduce X to Zero

Rain Hu
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int total = accumulate(nums.begin(), nums.end(), 0);
        int target = total - x;
        int left = 0, right = 0, res = -1, n = nums.size();
        int curr = 0;
        if (target == 0) res = 0;  // 注意要處理 boundary condition
        while (right < n) {
            curr += nums[right++];
            while (curr > target && left < right) {
                curr -= nums[left++];
            }
            if (curr == target) {
                res = max(res, right-left);
            }
        }
        return res == -1 ? -1 : n - res;  // 最後要將長度轉回來
    }
};

Share this post on:

Previous
[LeetCode] 2516. Take K of Each Character From Left and Right
Next
[LeetCode] 1838. Frequency of the Most Frequent Element