Skip to content

Commit 4908b1c

Browse files
authored
Create 1658-minimum-operations-to-reduce-x-to-zero.kt
1 parent f3e4c67 commit 4908b1c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
fun minOperations(nums: IntArray, x: Int): Int {
3+
var left = 0
4+
var max = -1
5+
var cur = 0
6+
var target = nums.sum()!! - x
7+
8+
for (right in 0 until nums.size) {
9+
cur += nums[right]
10+
11+
while (left <= right && cur > target) {
12+
cur -= nums[left++]
13+
}
14+
15+
if (cur == target) {
16+
max = maxOf(max, right - left + 1)
17+
}
18+
}
19+
20+
return if (max == -1) -1 else nums.size - max
21+
}
22+
}

0 commit comments

Comments
 (0)