Skip to content

Commit c95dec8

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (29.51%), Memory - 17.6 MB (98.13%)
1 parent f51c0d9 commit c95dec8

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<p>You are given an integer array <code>nums</code>.</p>
2+
3+
<p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p>
4+
5+
<ol>
6+
<li>All elements in the subarray are <strong>unique</strong>.</li>
7+
<li>The sum of the elements in the subarray is <strong>maximized</strong>.</li>
8+
</ol>
9+
10+
<p>Return the <strong>maximum sum</strong> of such a subarray.</p>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
15+
<div class="example-block">
16+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p>
17+
18+
<p><strong>Output:</strong> <span class="example-io">15</span></p>
19+
20+
<p><strong>Explanation:</strong></p>
21+
22+
<p>Select the entire array without deleting any element to obtain the maximum sum.</p>
23+
</div>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<div class="example-block">
28+
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p>
29+
30+
<p><strong>Output:</strong> 1</p>
31+
32+
<p><strong>Explanation:</strong></p>
33+
34+
<p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p>
35+
</div>
36+
37+
<p><strong class="example">Example 3:</strong></p>
38+
39+
<div class="example-block">
40+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p>
41+
42+
<p><strong>Output:</strong> 3</p>
43+
44+
<p><strong>Explanation:</strong></p>
45+
46+
<p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p>
47+
</div>
48+
49+
<p>&nbsp;</p>
50+
<p><strong>Constraints:</strong></p>
51+
52+
<ul>
53+
<li><code>1 &lt;= nums.length &lt;= 100</code></li>
54+
<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>
55+
</ul>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Approach: Greedy - Duplicate Removal for Positive Numbers
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def maxSum(self, nums: List[int]) -> int:
8+
pos_num_set = set([num for num in nums if num > 0])
9+
return max(nums) if len(pos_num_set) == 0 else sum(pos_num_set)
10+

0 commit comments

Comments
 (0)