FastPrepMaximum Sum Unique Subarray of Length K

Maximum Sum Unique Subarray of Length K

NetApp logoNetApp● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an integer array nums and an integer k, return the maximum sum among contiguous subarrays of exactly k elements whose values are all distinct.

If no qualifying subarray exists, return 0. A qualifying subarray may have a negative sum; in that case return the largest such negative sum rather than zero.

Function

maximumUniqueSubarraySum(nums: int[], k: int) → long

Examples

Example 1

nums = [3,2,2,3,4,6,7,7,-1]k = 4return = 20

The distinct window [3,4,6,7] has sum 20.

Example 2

nums = [5,5,5,5,5]k = 3return = 0

Every length-three window repeats 5, so none qualifies.

Constraints

  • 1 <= k <= nums.length <= 200000
  • -10^9 <= nums[i] <= 10^9
  • The answer fits in a signed 64-bit integer.

Source note: Interview prompt excerpt preserved as source evidence.

See NetApp hiring insights
public long maximumUniqueSubarraySum(int[] nums, int k) {
    // Write your code here.
}
nums[3,2,2,3,4,6,7,7,-1]
k4
expected20
Checking account…