
Problem Statement
Given an integer array nums
and an integer k
, the task is to find the maximum sum of all k-length subarrays of nums
, with each subarray satisfying a specific condition: each element in the subarray must be unique. A subarray is defined as a sequence of contiguous elements within the main array and is non-empty by definition. If a k-length subarray adheres to the uniqueness condition, we calculate its sum, and out of all such possible subarrays, we return the maximum sum. If no subarray meets the required conditions of uniqueness, the function should return 0
.
Examples
Example 1
Input:
nums = [1,5,4,2,9,9,9], k = 3
Output:
15
Explanation:
The subarrays of nums with length 3 are: - [1,5,4] which meets the requirements and has a sum of 10. - [5,4,2] which meets the requirements and has a sum of 11. - [4,2,9] which meets the requirements and has a sum of 15. - [2,9,9] which does not meet the requirements because the element 9 is repeated. - [9,9,9] which does not meet the requirements because the element 9 is repeated. We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions
Example 2
Input:
nums = [4,4,4], k = 3
Output:
0
Explanation:
The subarrays of nums with length 3 are: - [4,4,4] which does not meet the requirements because the element 4 is repeated. We return 0 because no subarrays meet the conditions.
Constraints
1 <= k <= nums.length <= 105
1 <= nums[i] <= 105
Approach and Intuition
To solve this problem efficiently, understanding the subtleties of dynamic windows and the uniqueness of elements within those windows is key. Here's a step-by-step approach leveraging the sliding window technique and hashmaps:
Sliding Window Preparation:
- We utilize a sliding window of size
k
to traverse through the array. The sliding window will help us check subarrays of exactlyk
elements consecutively. - To maintain and check the uniqueness of elements within the window, we use a hashmap (or dictionary). The hashmap stores each number and its frequency within the current window.
- We utilize a sliding window of size
Initial Setup:
- Initialize the hashmap and variables for the current sum of the window and the maximum sum found.
- Start by filling up the first window (the first
k
elements of the array) and update the hashmap and the current sum accordingly.
Sliding the Window:
- Move the window one element at a time from left to right. This involves adding one new element from the right and removing one element from the left.
- Update the hashmap to reflect this change, i.e., increase the count of the new element and decrease the count of the removed element.
- Adjust the current sum by adding the new element and subtracting the removed element.
Checking Conditions and Updating the Maximum Sum:
- After adjusting the window for each move, check if all elements within the window are unique by verifying that all values in the hashmap are equal to 1.
- If uniqueness is confirmed, compare and update the maximum sum with the current sum of the window.
- If not all elements are unique, skip to the next iteration.
Result Compilation:
- After processing all possible windows, the maximum sum recorded (which was continuously updated during unique window checks) is our result.
- If no valid window was found, the maximum sum would remain at
0
.
Given the constraints, sizing up to 1 <= k <= nums.length <= 105
and 1 <= nums[i] <= 105
, the approach ensures we manage time complexity effectively. By leveraging the sliding window and hashmap, we achieve an efficient solution that primarily works in O(n) time complexity, where n
is the length of nums
. This is because each element is processed a limited number of times (essentially twice — once added and once removed). Hence, the procedure is well-tuned to accommodate even larger sizes of the input array nums
.
Solutions
- C++
- Java
- Python
class Solution {
public:
long long findMaxSubarraySum(vector<int>& arr, int k) {
long long maxSum = 0;
long long sum = 0;
int start = 0;
int finish = 0;
unordered_map<int, int> lastIndex;
while (finish < arr.size()) {
int currentNum = arr[finish];
int previousIndex =
(lastIndex.count(currentNum) ? lastIndex[currentNum] : -1);
while (start <= previousIndex || finish - start + 1 > k) {
sum -= arr[start];
start++;
}
lastIndex[currentNum] = finish;
sum += arr[finish];
if (finish - start + 1 == k) {
maxSum = max(maxSum, sum);
}
finish++;
}
return maxSum;
}
};
The provided C++ code implements a function to find the maximum sum of a subarray of length k
, where each element in the subarray is unique. Here's the step-by-step flow:
- Initialize
maxSum
to store the maximum sum of any valid subarray andsum
to maintain the current subarray sum. Both are set to zero initially. - Use two pointers,
start
andfinish
, to maintain the current subarray window. - A hash map
lastIndex
keeps track of the most recent index of each element within the window.
During the iteration:
Loop through the array using the
finish
pointer. For each element inarr
at indexfinish
:- Check if the
currentNum
has appeared before usinglastIndex
. If it has, get the index, otherwise set it to -1.
- Check if the
Adjust the window if the current number has appeared within the window (
start
tofinish
) or if the window size exceedsk
:- Subtract the element at
start
fromsum
and increment thestart
pointer.
- Subtract the element at
Update the
lastIndex
for the current number tofinish
and add the number to thesum
.Every time the window size hits
k
, compare the currentsum
withmaxSum
and updatemaxSum
if the current is greater.Continue until the
finish
pointer reaches the end of the array. The function returnsmaxSum
, which holds the maximum sum of all uniquek
-length subarrays.
The use of a hashmap allows for efficient checking of previous occurrences of numbers within the subarray, effectively maintaining the uniqueness constraint. This approach ensures that the algorithm efficiently computes the maximum possible sum without revisits or redundancy, even for complex input scenarios.
class Solution {
public long findMaxSumSubarray(int[] array, int maxLen) {
long maxSum = 0;
long windowSum = 0;
int start = 0;
int finish = 0;
HashMap<Integer, Integer> lastPosition = new HashMap<>();
while (finish < array.length) {
int currentNumber = array[finish];
int prevIndex = lastPosition.getOrDefault(currentNumber, -1);
// Adjust the window if number is repeated or window size exceeded
while (start <= prevIndex || finish - start + 1 > maxLen) {
windowSum -= array[start];
start++;
}
lastPosition.put(currentNumber, finish);
windowSum += array[finish];
if (finish - start + 1 == maxLen) {
maxSum = Math.max(maxSum, windowSum);
}
finish++;
}
return maxSum;
}
}
The provided Java program attempts to find the maximum sum of subarrays that have distinct elements, with each subarray having a length specified by maxLen
. The approach uses a sliding window with a hashmap to keep track of the last index where each element was located. This allows the identification and management of subarrays that contain unique values only.
Here's a breakdown of how the solution works:
- Initialize
maxSum
to track the highest sum of a subarray, andwindowSum
to track the sum of the current window or subarray. - Start iterating through the array using the
finish
pointer, treating it as the end of your current subarray. - Retrieve the current number from the array and check when it was last encountered using a hashmap.
- If a number repeats within the subarray, or if the subarray's length exceeds
maxLen
, adjust thestart
pointer to maintain the distinctness by moving it past the last occurrence of the repeating number, thereby ensuring all elements in the window are unique. - Update the hashmap with the latest occurrence of the current number.
- If the subarray meets the desired length
maxLen
, check if its sum (windowSum
) is greater than the previously recordedmaxSum
. - Slide the
finish
pointer to continue examining the next potential subarray until the end of the array is reached.
Upon completion, maxSum
holds the value of the maximum sum of a subarray with distinct elements and length maxLen
.
Note: Use efficient hashmap operations to quickly look up and update the positions of the elements to ensure the solution remains optimal in terms of runtime, especially for large inputs.
class Solution:
def findMaxSumOfSubarray(self, numbers: List[int], max_size: int) -> int:
maximum_sum = 0
window_sum = 0
window_start = 0
window_end = 0
index_map = {}
while window_end < len(numbers):
value_at_end = numbers[window_end]
previous_index = index_map.get(value_at_end, -1)
# Adjust the window if the number already exists or the window exceeds the limit
while window_start <= previous_index or window_end - window_start + 1 > max_size:
window_sum -= numbers[window_start]
window_start += 1
index_map[value_at_end] = window_end
window_sum += numbers[window_end]
if window_end - window_start + 1 == max_size:
maximum_sum = max(maximum_sum, window_sum)
window_end += 1
return maximum_sum
For your task of finding the maximum sum of distinct subarrays with a length of k
using Python, you can leverage the sliding window technique and hashing. This approach ensures that each element in the subarray is unique and efficiently computes the maximum sum possible for the specified length. Here’s a walkthrough of the implemented solution:
Initialize Variables: Set
maximum_sum
andwindow_sum
to 0 for tracking the sums. Usewindow_start
andwindow_end
to define the current window boundaries. Createindex_map
to store the latest indices of elements to ensure distinct values in the subarray.Traverse the Array: Loop over the array using
window_end
as your iterator. For each iteration:- Retrieve the element at the current
window_end
. - Check its last occurrence using
index_map
. If it has appeared before and is within the current window, or if the window size exceedsk
, adjust thewindow_start
to the right until the subarray conditions are met (distinct elements, correct size).
- Retrieve the element at the current
Update the Window: After adjustments, update
index_map
for the current element and include the current element's value inwindow_sum
.Check for Maximum: If the window size equals
k
, compare and update themaximum_sum
with the currentwindow_sum
.Return Result: After processing all elements, return
maximum_sum
which will be the highest sum of any subarray of sizek
with all distinct elements.
This method is efficient because it minimally adjusts the window to exclude repeated values and its size exceeds k
, ensuring that each subarray considered for the maximum sum calculation is valid per the problem constraints. The use of a hashmap (index_map
) for tracking the indices of last occurrences of elements speeds up these checks and adjustments.
No comments yet.