-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum Operations to Reduce X to Zero.cpp
More file actions
76 lines (49 loc) · 1.66 KB
/
Copy pathMinimum Operations to Reduce X to Zero.cpp
File metadata and controls
76 lines (49 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
// Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
//Recursive:
class Solution {
public:
int mymin(int a, int b){
if(a<=b) return a;
return b;
}
void helper(vector<int>& nums, int i, int j, int x, int temp, int count, int& store){
if(temp>x) return ;
if(temp==x){
store = mymin(store, count);
return;
}
if(i>j) return;
if(i<nums.size()){
helper(nums, i+1, j, x, temp+nums[i], count+1, store);
}
if(j>=0){
helper(nums, i, j-1, x, temp+nums[j], count+1, store);
}
return;
}
int minOperations(vector<int>& nums, int x) {
int store =INT_MAX;
helper(nums, 0, nums.size()-1, x, 0, 0, store);
if(store==INT_MAX) return -1;
return store;
}
};
///////
class Solution {
public:
int minOperations(vector<int>& nums, int x) {
int totalSum = 0;
for(auto it: nums) totalSum+=it;
int maxLength = -1;
int currSum=0;
for(int l=0, r=0; r<nums.size();++r){
currSum +=nums[r];
while(l<=r && currSum>totalSum-x) currSum-=nums[l++];
if(currSum==totalSum-x){
maxLength = max(maxLength, r-l+1);
}
}
return maxLength ==-1? -1:nums.size()-maxLength;
}
};