generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
48 lines (40 loc) · 849 Bytes
/
solution.cpp
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
#include <vector>
class Solution {
public:
int minOperations(std::vector<int>& nums, int x) {
int res = -1;
const int n = nums.size();
int xx = x;
int ll = 0;
int rr = n - 1;
while (ll < n) {
xx -= nums[ll];
if (xx <= 0) {
if (xx == 0) {
int new_res = ll + 1;
res = res > 0 ? std::min(res, new_res) : new_res;
}
break;
}
++ll;
}
if (ll == n) --ll;
while (ll >= 0) {
xx += nums[ll];
--ll;
while (xx < 0 && rr < n - 1) {
xx += nums[rr];
++rr;
}
while (rr > ll && xx >= nums[rr]) {
xx -= nums[rr];
if (xx == 0) {
int new_res = ll + 1 + n - rr;
res = res > 0 ? std::min(res, new_res) : new_res;
}
--rr;
}
}
return res;
}
};