Problem Statement
You are tasked with identifying a contiguous subarray from a given array of positive integers, where all elements are unique. The objective is to find such a subarray such that if you were to 'erase' this part of the array, the sum of its values would be maximized. The score of erasing a subarray is computed by summing up all its elements. Your goal is to compute the maximum score possible by erasing exactly one subarray which must consist exclusively of unique elements.
Examples
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
Approach and Intuition
Given the nature of the problem, with its focus on maximizing a sum of unique-element subarrays, a logical approach involves the use of a sliding window technique combined with tracking mechanisms for elements to ensure uniqueness. Here's a step-by-step breakdown of the proposed method:
- Initialize two pointers to define the window - commonly
left
andright
pointers. - Use a hash map or set to keep track of the elements in the current window and ensure all elements are unique.
- Expand the
right
pointer to extend the window until a duplicate element is encountered or the end of the array is reached. - As you expand the window, keep updating the current sum of the window.
- When a duplicate is encountered, move the
left
pointer to shrink the window until the duplicate is excluded, ensuring the uniqueness of elements within the window. - Continuously update and track the maximum sum encountered.
- Continue this process until the
right
pointer has traversed the entire array.
This technique leverages the efficiency of the sliding window to check each element once, adjusting the window boundaries as duplicates are encountered and removed. By doing this, we ensure that the time complexity is efficient, ideally near linear relative to the size of the input array.
The intuition behind using a sliding window here is due to the need for exploring subarrays of variable sizes to find the maximum sum possible. Tracking the largest sum during this traversal allows for efficient determination of the optimal score in a single pass of the array, minimizing unnecessary recalculations.
Solutions
- C++
- Java
class Solution {
public:
int maxUniqueSubarraySum(vector<int>& nums) {
int length = nums.size(), maxSum = 0, low = 0, maxVal = 10001;
vector<int> indexes(maxVal, -1);
vector<int> cumulativeSum(length + 1, 0);
for (int high = 0; high < length; high++) {
int val = nums[high];
cumulativeSum[high + 1] = cumulativeSum[high] + val;
if (indexes[val] >= 0) {
low = max(low, indexes[val] + 1);
}
maxSum = max(maxSum, cumulativeSum[high + 1] - cumulativeSum[low]);
indexes[val] = high;
}
return maxSum;
}
};
In this solution, the goal is to find the maximum sum of any contiguous subarray in a given list of integers, where all integers are unique within the subarray. The approach utilizes a sliding window technique combined with a hashmap to keep track of the most recent indices of each number within the array.
Follow these steps to understand the method implemented in the C++ code:
- Initialize variables for the size of the array (
length
), maximum sum identified (maxSum
), the starting point of the sliding window (low
), and establish a limit (maxVal
) to create a sufficiently large vector to keep track of indices. - Create two vectors:
indexes
initialized with -1 to keep track of the latest index of each number, andcumulativeSum
to store the running sum of elements up to current index for easy calculation of sum within a range. - Iterate through the array using an index (
high
) that represents the end of the current window:- Update
cumulativeSum
for current index by adding the value atnums[high]
. - If the current number was seen before (i.e.,
indexes[nums[high]]
is not -1), updatelow
to ensure no numbers are repeated in the current subarray. - Calculate the sum of the current subarray by subtracting the cumulative sum at the start of the window (
low
) from that at the end (high + 1
). UpdatemaxSum
if this new sum is greater. - Update the last seen index of current number in
indexes
.
- Update
- Return
maxSum
as the result which holds the maximum sum of a unique-element subarray.
With this efficient approach, each element in the array is processed in constant time, leading to a solution that scales linearly with the size of the input array.
class Solution {
public int maxUniqueSubarray(int[] elements) {
int len = elements.length, maxVal = 10001;
int[] lastIndex = new int[maxVal];
int[] accumSum = new int[len + 1];
Arrays.fill(lastIndex, -1);
int maxSum = 0, windowStart = 0;
for (int windowEnd = 0; windowEnd < len; windowEnd++) {
int element = elements[windowEnd];
accumSum[windowEnd + 1] = accumSum[windowEnd] + element;
if (lastIndex[element] != -1) {
windowStart = Math.max(windowStart, lastIndex[element] + 1);
}
maxSum = Math.max(maxSum, accumSum[windowEnd + 1] - accumSum[windowStart]);
lastIndex[element] = windowEnd;
}
return maxSum;
}
}
The provided Java code implements a solution to find the maximum score of a unique subarray from a given array of integers. The objective is to select a contiguous subarray such that no value appears more than once, and its sum is the highest possible. The approach taken can be summarized as follows:
- Initialize an array
lastIndex
to store the last occurrence index of each element within the range of potential values in theelements
array. The length oflastIndex
is set to a constantmaxVal
, considering the maximum possible value in theelements
array +1 to handle the indexing conveniently. - Utilize an auxiliary array
accumSum
to hold the accumulative sum of the elements, which aids in efficiently calculating the sum of any subarray. - Use two pointers,
windowStart
andwindowEnd
, to manage the sliding window's bounds. - Iterate through the
elements
usingwindowEnd
. During each iteration:- Update the accumulative sum in
accumSum
. - If the current element has appeared earlier (i.e., its index is recorded in
lastIndex
), adjustwindowStart
to ensure all elements in the current window are unique. - Calculate the current subarray's sum by subtracting the accumulative sum at
windowStart
from the accumulative sum atwindowEnd + 1
. UpdatemaxSum
if the current subarray's sum is greater. - Update the
lastIndex
of the current element to the currentwindowEnd
to track its most recent appearance.
- Update the accumulative sum in
- The algorithm ultimately returns
maxSum
, which is the maximum sum of any unique subarray found during the iteration.
This approach efficiently tracks and updates the required values using a combination of auxiliary data structures and a sliding window technique, ensuring that each element contributes to at most one unique subarray in consideration for the maximum sum.
No comments yet.