Maximum Sum of Distinct Subarrays With Length K

Medium

Description

Given an integer array nums and an integer k, find the maximum subarray sum of all subarrays of length k with all distinct elements.

Examples

Input:nums = [1,5,4,2,9,9,9], k = 3
Output:15
Explanation:

[5,4,2] and [4,2,9] have distinct elements.

Input:nums = [4,4,4], k = 3
Output:0
Explanation:

Edge case returning zero.

Input:nums = [2,1,3,1,2,4], k = 4
Output:10
Explanation:

The subarrays of length 4 are [2,1,3,1], [1,3,1,2], [3,1,2,4]. Only [3,1,2,4] has all distinct elements, with sum 3+1+2+4 = 10.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!