🎉 One-stop destination for all your technical interview Preparation 🎉
XXXOOOXX
, here if we need to find sum of all X
we can simply do it with total sum - sum of O
, same idea can be used in this problem.sum = reqSum
, Where reqSum = totalSumOfArray - x
total length - max length of subarray
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;
}
};