Amazon|OA|Max Subarray Sum of size k that has K distinct Elements
Anonymous User
8875

Given An Array Of N integers and a Number K return max sum of subarray of size k that has K Distinct Elements. if it does not exist return -1.

Test Case:
[1,2,3,4,4,3,2,1],k=3
Output:
9
[1,2,3],[2,3,4],[4,3,2],[3,2,1] are valid subarrays as they have k distinct elements.max sum among them is 9

Test Case:
[1,2,2] k=3
Output:
-1
No valid subarray of length k exist that has all k elements unique.

Constrainst:
1<=n<=1e5
k<=n
1<=arr[i]<=1e9

How to solve It Optimally? I did brute force and got tle.

Comments (15)