Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

1658. Minimum Operations to Reduce X to Zero 🌟🌟

Prefix and Suffix Sum with map

Sliding Window

Code

class Solution {
public:
    int minOperations(vector<int>& nums, int x)
    {
        int n = nums.size();

        int reqSum = 0, windowSum = 0;
        reqSum = accumulate(nums.begin(), nums.end(), 0);
        reqSum -= x;
        // if required sum is 0, then total array length is answer.
        if (reqSum == 0) return n;

        int i = 0, maxLen = 0;
        // find sliding window whose sum=reqSum and length is maximum
        for (int j = 0; j < n; j++) {
            windowSum += nums[j];
            while (i < n && windowSum > reqSum) {
                // if window sum exceeds required sum, reduce window size from front
                windowSum -= nums[i];
                i++;
            }
            if (windowSum == reqSum) {
                // we found one of the subarray with required sum
                maxLen = max(maxLen, j - i + 1);
            }
        }

        // if don't find any subarray of required sum, return -1
        if (maxLen == 0) return -1;
        // else return n-maxLen
        return n - maxLen;
    }
};