problem
Prefix sum with Two Pointers
class Solution {
fun minOperations(nums: IntArray, x: Int): Int {
val size = nums.size
val prefix = IntArray(size + 1) { 0 }
for (i in 1..size) {
prefix[i] = prefix[i - 1] + nums[i - 1]
}
val total = prefix[size]
var start = 0
var end = 1
var answer = Int.MAX_VALUE
while (end <= size && start <= end) {
val sub = prefix[end] - prefix[start]
if (sub == total - x) {
answer = minOf((size - end) + start, answer)
end++
start++
} else if (sub < total - x) {
end++
} else {
start++
}
}
return if (answer == Int.MAX_VALUE) -1
else answer
}
}
Prefix sum with Hash Table
class Solution {
fun minOperations(nums: IntArray, x: Int): Int {
val target = nums.sum() - x
if (target == 0) return nums.size
val table = mutableMapOf<Int, Int>()
table[0] = -1
var sum = 0
var answer = Int.MIN_VALUE
nums.forEachIndexed { index, num ->
sum += num
val temp = table[sum - target]
if (temp != null) {
answer = maxOf(answer, index - temp)
}
table[sum] = index
}
return if (answer == Int.MIN_VALUE) -1
else nums.size - answer
}
}