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.
Return the maximum score you can get by erasing exactly one subarray.
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)
.
Example 1:
Input: nums = [4,2,4,5,6] Output: 17 Explanation: The optimal subarray here is [2,4,5,6].
Example 2:
Input: nums = [5,2,1,2,5,2,1,2,5] Output: 8 Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
Companies:
Cashfree
Related Topics:
Array, Hash Table, Sliding Window
Similar Questions:
// OJ: https://leetcode.com/problems/maximum-erasure-value/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int maximumUniqueSubarray(vector<int>& A) {
int i = 0, ans = 0, N = A.size(); // window [i, j] is a window which only contains unique elements.
unordered_map<int, int> m; // number -> index of last occurrence.
vector<int> sum(N + 1);
partial_sum(begin(A), end(A), begin(sum) + 1);
for (int j = 0; j < N; ++j) {
if (m.count(A[j])) i = max(i, m[A[j]] + 1);
m[A[j]] = j;
ans = max(ans, sum[j + 1] - sum[i]);
}
return ans;
}
};
// OJ: https://leetcode.com/problems/maximum-erasure-value/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(U) where U is the number of unique elements in `A`
class Solution {
public:
int maximumUniqueSubarray(vector<int>& A) {
int ans = 0, N = A.size(), sum = 0;
unordered_set<int> s;
for (int i = 0, j = 0; j < N; ++j) {
while (s.count(A[j])) {
s.erase(A[i]);
sum -= A[i++];
}
s.insert(A[j]);
sum += A[j];
ans = max(ans, sum);
}
return ans;
}
};
Check out "C++ Maximum Sliding Window Cheatsheet Template!"
// OJ: https://leetcode.com/problems/maximum-erasure-value/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(U) where U is the number of unique elements in `A`
class Solution {
public:
int maximumUniqueSubarray(vector<int>& A) {
int i = 0, j = 0, N = A.size(), ans = 0, dup = 0, sum = 0;
unordered_map<int, int> cnt;
while (j < N) {
dup += ++cnt[A[j]] == 2;
sum += A[j++];
while (dup) {
dup -= --cnt[A[i]] == 1;
sum -= A[i++];
}
ans = max(ans, sum);
}
return ans;
}
};
https://leetcode.com/problems/maximum-erasure-value/discuss/1504271