-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1658.cpp
More file actions
27 lines (26 loc) · 730 Bytes
/
1658.cpp
File metadata and controls
27 lines (26 loc) · 730 Bytes
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
class Solution {
public:
int minOperations(vector<int>& nums, int x) {
// maximum lenght of subarray equal to sum - x
int sum = 0;
for (auto& num : nums) sum += num;
int target = sum - x;
if (target < 0) return -1;
int n = nums.size();
int left = 0;
int curr = 0;
int res = -1;
for (int right = 0; right < n; ++right) {
curr += nums[right];
while (curr > target) {
curr -= nums[left];
left++;
}
if (curr == target) {
res = max(res, right - left + 1);
}
}
if (res == -1) return -1;
return n - res;
}
};