[LeetCode] Maximum Unique Subarray Sum After Deletion

3487. Maximum Unique Subarray Sum After Deletion

You are given an integer array nums.

You are allowed to delete any number of elements from nums without making it empty. After performing the deletions, select a subarray of nums such that:

  1. All elements in the subarray are unique.
  2. The sum of the elements in the subarray is maximized.

Return the maximum sum of such a subarray.

go
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
package main

import "sort"

func maxSum(nums []int) int {
ma := maxElement(nums)
if ma <= 0 {
return ma
}

us := make(map[int]bool)
res := 0

for _, n := range nums {
if n > 0 && !us[n] {
res += n
us[n] = true
}
}

return res
}

func maxElement(arr []int) int {
if len(arr) == 0 {
return 0
}
sort.Ints(arr)
return arr[len(arr)-1]
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/16/PS/LeetCode/maximum-unique-subarray-sum-after-deletion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment