-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path25_Maximum_Unique_Subarray_Sum_After_Deletion.cpp
More file actions
91 lines (63 loc) · 1.8 KB
/
Copy path25_Maximum_Unique_Subarray_Sum_After_Deletion.cpp
File metadata and controls
91 lines (63 loc) · 1.8 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// 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:
// 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
class Solution
{
public:
int maxSum(vector<int> &nums)
{
bool allNegative = true;
int maxValue = INT_MIN;
for (int n : nums)
{
if (n >= 0)
{
allNegative = false;
}
if (n > maxValue)
{
maxValue = n;
}
}
if (allNegative)
return maxValue;
bool seen[101] = {false};
for (int n : nums)
{
if (n >= 0 && n < 101)
{
seen[n] = true;
}
}
int sum = 0;
for (int i = 1; i < 101; i++)
{
if (seen[i])
{
sum += i;
}
}
return sum;
}
};