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 <= 1051 <= nums[i] <= 104Solution 1:
This can be solved in multiple ways, the easiest is to maintain a queue and verify the value read from the given nums array is unique. If not remove the element and the count from the queue and the current count respectively.
class Solution {
public int maximumUniqueSubarray(int[] nums) {
Queue<Integer> q = new LinkedList<>();
int maxCount = 0;
int count = 0;
for(int i =0;i< nums.length;i++){
if(!q.contains(nums[i])){
count += nums[i];
q.add(nums[i]);
}else {
maxCount = count>maxCount ? count: maxCount;
while(!q.isEmpty() && q.peek() != nums[i]){
int del = q.remove();
count -= del;
}
q.remove();
q.add(nums[i]);
}
}
maxCount = count>maxCount ? count: maxCount;
return maxCount;
}
} Solution 2:
The optimal way to solve this would be to use two pointer approach, which can be solved using O(n) time and O(m) space where m is the number of unique elements.
public int maximumUniqueSubarray(int[] nums) {
int maxScore = 0, currScore = 0;
Set<Integer> set = new HashSet<>();
for (int l=0, r=0; r<nums.length; r++) {
while (!set.add(nums[r])) {
currScore -= nums[l];
set.remove(nums[l++]);
}
currScore += nums[r];
maxScore = Math.max(maxScore, currScore);
}
return maxScore;
} Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.