Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The question here asks to minimize the operations to reduce X to zero by taking elements from either side. Let us take total sum of the array be totalSum. If X is reduced from either side, means remaining array will have sum equal to totalSum-X. As operations has to be minimized, so this question is equivalent to finding maximum size subarray having sum as totalSum-X.
- */
- class Solution {
- public:
- int minOperations(vector<int>& nums, int x) {
- int sum=0;
- for(int itr:nums){
- sum+=itr;
- }
- if(sum==x) return nums.size();
- sum-=x;
- int ans=-1,l=0;
- int cur=0;
- for(int i=0;i<nums.size();i++){
- cur+=nums[i];
- if(i==2) cout<<cur<<endl;
- while(l<i && cur>sum){
- cur-=nums[l];
- l++;
- }
- if(cur==sum) ans=max(ans,i-l+1);
- }
- if(ans==-1) return -1;
- else return nums.size()-ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement