problem
Prefix sum with two pointers - 1
class Solution {
fun maximumUniqueSubarray(nums: IntArray): Int {
val size = nums.size
val prefixs = IntArray(size + 1) { 0 }
for (i in 1..size) {
prefixs[i] += prefixs[i - 1] + nums[i - 1]
}
val table = mutableMapOf<Int, Int>()
var start = 0
var answer = 0
nums.forEachIndexed { end, num ->
val temp = table[num]
if (temp != null) {
start = maxOf(start, temp + 1)
}
answer = maxOf(answer, prefixs[end + 1] - prefixs[start])
table[num] = end
}
return answer
}
}
Prefix sum with two pointers - 2
class Solution {
fun maximumUniqueSubarray(nums: IntArray): Int {
val table = mutableMapOf<Int, Int>()
var left = 0
var sum = 0
var answer = 0
nums.forEachIndexed { right, num ->
val dupIndex = table[num]
if (dupIndex != null) {
while (left <= dupIndex) {
sum -= nums[left++]
}
}
table[num] = right
sum += num
answer = maxOf(answer, sum)
}
return answer
}
}
Hash set with two pointers
class Solution {
fun maximumUniqueSubarray(nums: IntArray): Int {
val set = mutableSetOf<Int>()
val size = nums.size
var right = 0
var left = 0
var answer = 0
var sum = 0
while (right < size) {
if (!set.contains(nums[right])) {
set.add(nums[right])
sum += nums[right++]
answer = maxOf(answer, sum)
} else {
set.remove(nums[left])
sum -= nums[left++]
}
}
return answer
}
}