3487. Maximum Unique Subarray Sum After Deletion
Description
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:
- All elements in the subarray are unique.
- The sum of the elements in the subarray is maximized.
Return the maximum sum of such a subarray.
Example 1:
Input: nums = [1,2,3,4,5]
Output: 15
Explanation:
Select the entire array without deleting any element to obtain the maximum sum.
Example 2:
Input: nums = [1,1,0,1,1]
Output: 1
Explanation:
Delete the element nums[0] == 1
, nums[1] == 1
, nums[2] == 0
, and nums[3] == 1
. Select the entire array [1]
to obtain the maximum sum.
Example 3:
Input: nums = [1,2,-1,-2,1,0,-1]
Output: 3
Explanation:
Delete the elements nums[2] == -1
and nums[3] == -2
, and select the subarray [2, 1]
from [1, 2, 1, 0, -1]
to obtain the maximum sum.
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100
Solutions
Solution 1: Greedy + Hash Table
We first find the maximum value \(\textit{mx}\) in the array. If \(\textit{mx} \leq 0\), then all elements in the array are less than or equal to 0. Since we need to select a non-empty subarray with the maximum element sum, the maximum element sum would be \(\textit{mx}\).
If \(\textit{mx} > 0\), then we need to find all distinct positive integers in the array such that their sum is maximized. We can use a hash table \(\textit{s}\) to record all distinct positive integers, and then iterate through the array, adding up all distinct positive integers.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|