Skip to content

Commit 50d6397

Browse files
committed
Sync LeetCode submission Runtime - 203 ms (65.63%), Memory - 28.9 MB (50.60%)
1 parent 27aed52 commit 50d6397

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

1813-maximum-erasure-value/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<p>You are given an array of positive integers <code>nums</code> and want to erase a subarray containing&nbsp;<strong>unique elements</strong>. The <strong>score</strong> you get by erasing the subarray is equal to the <strong>sum</strong> of its elements.</p>
2+
3+
<p>Return <em>the <strong>maximum score</strong> you can get by erasing <strong>exactly one</strong> subarray.</em></p>
4+
5+
<p>An array <code>b</code> is called to be a <span class="tex-font-style-it">subarray</span> of <code>a</code> if it forms a contiguous subsequence of <code>a</code>, that is, if it is equal to <code>a[l],a[l+1],...,a[r]</code> for some <code>(l,r)</code>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [4,2,4,5,6]
12+
<strong>Output:</strong> 17
13+
<strong>Explanation:</strong> The optimal subarray here is [2,4,5,6].
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [5,2,1,2,5,2,1,2,5]
20+
<strong>Output:</strong> 8
21+
<strong>Explanation:</strong> The optimal subarray here is [5,2,1] or [1,2,5].
22+
</pre>
23+
24+
<p>&nbsp;</p>
25+
<p><strong>Constraints:</strong></p>
26+
27+
<ul>
28+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
29+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
30+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach: Two Pointer
2+
3+
# Time: O(n)
4+
# Space: O(k), k = size of the unique elements in largest valid subarray
5+
6+
class Solution:
7+
def maximumUniqueSubarray(self, nums: List[int]) -> int:
8+
seen = set()
9+
curr_sum = 0
10+
max_sum = 0
11+
left = 0
12+
13+
for right in range(len(nums)):
14+
while nums[right] in seen:
15+
curr_sum -= nums[left]
16+
seen.remove(nums[left])
17+
left += 1
18+
19+
seen.add(nums[right])
20+
curr_sum += nums[right]
21+
22+
max_sum = max(max_sum, curr_sum)
23+
24+
return max_sum

0 commit comments

Comments
 (0)