Problem
You are given an integer array nums
and an integer k
. Find the maximum subarray sum of all the subarrays of nums
that meet the following conditions:
- The length of the subarray is
k
, and - All the elements of the subarray are distinct.
Return the maximum subarray sum of all the subarrays that meet the conditions_._ If no subarray meets the conditions, return 0
.
A subarray is a contiguous non-empty sequence of elements within an array.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Sliding window
Here is the approach:
- Initial Setup:
- We need to find subarrays of length
k
where all the elements are distinct. - Initialize
ans
to store the result (maximum subarray sum),currentSum
to keep the sum of the current window, andwindow
as a map to count the frequency of elements within the current window.
- We need to find subarrays of length
- Form the Initial Window:
- Loop through the first
k
elements of thenums
array. - Add each element to the
window
map and updatecurrentSum
by adding the element’s value. - After the loop, check if the size of the
window
(distinct elements) equalsk
:- If true, set
ans
tocurrentSum
as the initial valid subarray sum.
- If true, set
- Loop through the first
- Sliding Window Technique for the Rest of the Elements:
- Continue the loop for the rest of the array starting from index
k
. - For each new element, add it to the
window
and increment its frequency. - Remove the element that slides out from the left of the window by decrementing its frequency in the
window
:- If its frequency becomes zero, remove the element from the
window
.
- If its frequency becomes zero, remove the element from the
- Update
currentSum
by adding the new element and subtracting the element that slid out. - Check if the size of the
window
(distinct elements) equalsk
:- If true, update
ans
with the maximum value between the currentans
andcurrentSum
.
- If true, update
- Continue the loop for the rest of the array starting from index
- Return the Final Result:
- Return
ans
which holds the maximum subarray sum meeting the conditions.
- Return
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the array. Each element is processed a constant number of times (added and removed from the map). - 🧺 Space complexity:
O(k)
, used for storing elements in thewindow
map.