Taro Logo

Maximum Sum of Distinct Subarrays With Length K

#3 Most AskedMedium
1 view
Topics:
ArraysSliding Windows

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.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements inside the nums array, and can they include negative numbers or zeros?
  2. How large can the nums array be, and what is the maximum possible value for $k$?
  3. If there are no valid subarrays of length $k$ containing strictly unique elements, should the function return 0 as stated in the description?
  4. Can $k$ be larger than the total length of the nums array, and how should that case be handled?
  5. Are all elements in the array guaranteed to be standard integers, or could we encounter floating-point numbers or null values?

Brute Force Solution

Approach

The brute force approach for this problem is all about trying out every possible subarray of the required length. For each of these subarrays, we check if all the numbers are unique and if they are, we calculate the sum. Finally, we find the maximum sum among all valid subarrays.

Here's how the algorithm would work step-by-step:

  1. First, consider the first 'chunk' of numbers that has the required length.
  2. Check if all the numbers in this chunk are different from each other. If not, move on to the next chunk.
  3. If all the numbers in the chunk *are* different, add them up to get a sum.
  4. Remember this sum. It might be the biggest one we've seen so far.
  5. Now, slide the chunk over by one number, and look at the next set of numbers of the required length.
  6. Again, check if all numbers in this new chunk are different.
  7. If they are, add them up and compare that sum to the sum you remembered earlier.
  8. If the new sum is bigger, replace the remembered sum with this new bigger sum.
  9. Keep sliding the chunk and repeating the process until you've checked every possible chunk of the required length in the original set of numbers.
  10. After checking all the chunks, the sum you're remembering will be the biggest sum of a chunk with unique numbers that had the required length.

Code Implementation

def maximum_unique_subarray_brute_force(numbers, subarray_length):
    maximum_sum = 0
    
    # Iterate through all possible starting positions of the subarray
    for i in range(len(numbers) - subarray_length + 1):
        current_subarray = numbers[i:i + subarray_length]

        # Check for distinct elements
        if len(set(current_subarray)) == subarray_length:

            current_sum = sum(current_subarray)

            # Keep track of the maximum sum
            if current_sum > maximum_sum:
                maximum_sum = current_sum

    return maximum_sum

Big(O) Analysis

Time Complexity
O(n*k) – The algorithm iterates through all possible subarrays of length k within the input array of size n. For each subarray of length k, it checks for distinct elements which takes O(k) time in the worst case. Since there are approximately n such subarrays to check, the overall time complexity is O(n*k). Specifically, to check distinct elements, we may use a set that in the worst case goes up to a size of k.
Space Complexity
O(K) – The provided solution implicitly uses a sliding window approach where, in each iteration, it checks if the current subarray of length K contains distinct elements. To determine the uniqueness of the elements in the subarray, a hash set (or similar data structure) of size at most K is required to store the elements of the current subarray being examined. Therefore, the auxiliary space used depends on K, the length of the subarray. Consequently, the space complexity is O(K).

Optimal Solution

Approach

To find the highest possible total from a specific sized group of unique items, we can use a moving window strategy. Instead of recalculating every possible combination from scratch, we slide our view forward one item at a time, updating our running total and keeping track of duplicates instantly.

Here's how the algorithm would work step-by-step:

  1. Gather a group of items matching the exact target size starting from the very beginning of the collection.
  2. Check this initial group to ensure every single item inside it is completely unique and has no duplicates.
  3. If all items in the group are unique, calculate their total sum and keep that number in mind as your current record.
  4. Slide your view forward by dropping the oldest item at the back and bringing a brand new item in at the front.
  5. Instead of recounting everything, simply subtract the dropped item from your running total and add the new item.
  6. Keep track of how many times each item currently appears inside your active view so you always know immediately if a duplicate is present.
  7. Whenever your active view contains only unique items and its total sum beats your previous record, update your best record.
  8. Continue sliding forward until you reach the very end of the collection, then reveal the highest total you successfully recorded.

Code Implementation

from collections import defaultdict


def maximum_subarray_sum(input_array, target_window_size):
    maximum_recorded_sum = 0
    current_window_sum = 0
    element_frequency_map = defaultdict(int)

    # Establish the initial window of the target size from the beginning of the array.
    for index_pointer in range(target_window_size):
        current_element = input_array[index_pointer]
        element_frequency_map[current_element] += 1
        current_window_sum += current_element

    # Verify uniqueness of the initial window before recording the first valid sum.
    if len(element_frequency_map) == target_window_size:
        maximum_recorded_sum = current_window_sum

    # Slide the active window forward across the remainder of the collection.
    for index_pointer in range(target_window_size, len(input_array)):
        outgoing_element = input_array[index_pointer - target_window_size]
        incoming_element = input_array[index_pointer]

        element_frequency_map[outgoing_element] -= 1
        if element_frequency_map[outgoing_element] == 0:
            del element_frequency_map[outgoing_element]

        element_frequency_map[incoming_element] += 1
        current_window_sum += incoming_element - outgoing_element

        # Update the maximum record only when all elements in the current view are distinct.
        if len(element_frequency_map) == target_window_size:
            if current_window_sum > maximum_recorded_sum:
                maximum_recorded_sum = current_window_sum

    return maximum_recorded_sum

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of items in the collection. The algorithm first performs a single pass to build the initial window of size k, and then slides this window forward across the remaining elements one by one in linear fashion. Because we use a hash map or frequency tracker to instantly check for duplicates and update our running sum in constant time O(1) during each slide, we avoid any nested iteration. As we process each of the n items exactly once upon entry and exit from the window, the total operations scale linearly with n, simplifying directly to O(n).
Space Complexity
O(min(N, U)) – The auxiliary space is driven by the frequency map or hash set used to track how many times each item currently appears inside the active sliding window, where N is the total number of elements in the collection and U is the maximum number of unique elements possible. In the worst-case scenario where all elements are distinct within a window of size K, the hash map will store up to K elements, meaning the space complexity scales directly with the window size K or the number of unique elements. Additionally, a few primitive variables are used to maintain the running total and the best record, which only require constant extra space. Therefore, the overall auxiliary space complexity simplifies to Big O of K, or more precisely O(min(N, U)), reflecting the active items tracked at any single moment.

Edge Cases

Array length is less than k
How to Handle:
Return zero immediately since no valid subarray of length k can possibly exist in the input.
All elements in the array are identical
How to Handle:
The frequency map will detect duplicates within any window of length greater than one, ensuring zero is returned if k > 1.
Array contains negative numbers and zeros
How to Handle:
Maintain the current window sum accurately using standard arithmetic and allow negative sums since the problem permits them.
k equals 1
How to Handle:
Every single element forms a valid subarray of length k with unique elements, so the maximum element in the array is returned.
k equals the length of the array
How to Handle:
Check if all elements in the entire array are unique and return their total sum, or return zero if any duplicates exist.
Maximum-sized inputs with up to 100,000 elements
How to Handle:
Use a sliding window approach with a hash map or frequency array to ensure an efficient O(n) time complexity.
Integer overflow during sum calculation
How to Handle:
Use 64-bit integers for accumulating the subarray sums to prevent arithmetic overflow with large values.
No valid subarray exists with all unique elements of length k
How to Handle:
Initialize the maximum sum tracker to zero and return it since no valid condition was met throughout the iteration.
0/8 completed