Skip to content

Commit fa44a0a

Browse files
authored
Create Maximum Erasure Value.cpp
1 parent e005dbd commit fa44a0a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Leet Code */
2+
/* Title - Maximum Erasure Value */
3+
/* Created By - Akash Modak */
4+
/* Date - 14/06/2023 */
5+
6+
// You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
7+
8+
// Return the maximum score you can get by erasing exactly one subarray.
9+
10+
// An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).
11+
12+
13+
14+
// Example 1:
15+
16+
// Input: nums = [4,2,4,5,6]
17+
// Output: 17
18+
// Explanation: The optimal subarray here is [2,4,5,6].
19+
// Example 2:
20+
21+
// Input: nums = [5,2,1,2,5,2,1,2,5]
22+
// Output: 8
23+
// Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
24+
25+
class Solution {
26+
public:
27+
int maximumUniqueSubarray(vector<int>& nums) {
28+
unordered_set<int> s;
29+
int sum=0, maxSum=INT_MIN,start=0;
30+
for(int i=0;i<nums.size();i++){
31+
if(s.find(nums[i])!=s.end()){
32+
maxSum=max(sum,maxSum);
33+
while(start<i) {
34+
sum-=nums[start];
35+
s.erase(nums[start]);
36+
start++;
37+
if(nums[start-1]==nums[i]) break;
38+
}
39+
}
40+
s.insert(nums[i]);
41+
sum+=nums[i];
42+
}
43+
return maxSum<sum?sum:maxSum;
44+
}
45+
};

0 commit comments

Comments
 (0)