AlgoMaster Logo

Maximum Sum of Distinct Subarrays With Length K

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Sliding Window with Brute Force

Intuition:

To find the maximum sum of distinct subarrays of a particular length ( K ), we can use a sliding window. However, a simple brute force approach involves generating all possible subarrays of length ( K ) and ensuring that each subarray consists of distinct elements. For each valid subarray, compute the sum and keep track of the maximum sum found.

Steps:

  1. Iterate over the array, building subarrays containing ( K ) elements.
  2. For each subarray, check if all the elements are distinct.
  3. If yes, compute the sum of the subarray. Update the maximum sum if it's larger than the current maximum.
  4. Return the maximum sum found.

Code:

2. Sliding Window with HashSet

Intuition:

An improved approach still uses a sliding window but leverages a HashSet to maintain a set of distinct elements in the current window. This avoids the need to check distinctness explicitly for each subarray by allowing additions and removals of elements from the window in constant time.

Steps:

  1. Maintain a sliding window with two pointers, ( left ) and ( right ).
  2. Use a HashSet to maintain the distinct elements within the current window.
  3. Iterate over the array and attempt to build a window of size ( K ).
  4. If you've successfully built such a window with all distinct elements, compute the sum and update the maximum sum if necessary.
  5. Move the window by adjusting ( left ).

Code: