Maximum Sum of Almost Unique Subarray

You are given an integer array nums and two positive integers m and k.

Return the maximum sum out of all almost unique subarrays of length k of nums. If no such subarray exists, return 0.

A subarray of nums is almost unique if it contains at least m distinct elements.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1
Inputnums = [2,6,7,3,1,7], m = 3, k = 4
Output18
There are 3 almost unique subarrays of size k = 4; among them, [2, 6, 7, 3] has the maximum sum of 18.
Example 2
Inputnums = [5,9,9,2,4,5,4], m = 1, k = 3
Output23
There are 5 almost unique subarrays of size k, and [5, 9, 9] has the maximum sum of 23.

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • 1 <= m <= k <= nums.length
  • 1 <= nums[i] <= 10^9

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate