Skip to contentKEEP THE CRAFTTHE SANCTUARY

Maximum Sum of a Distinct Length-K Subarray

Find the largest sum of k consecutive values that are all different.

The problem

Implement Solution.maximumSubarraySum(nums, k). Look at every contiguous subarray of exactly k values in which no value appears twice, and return the largest sum among them. Return 0 if there is no such subarray. For example, nums = [1, 5, 4, 2, 9, 9, 9] with k = 3 gives 15 from [4, 2, 9]; [2, 9, 9] and [9, 9, 9] would be larger but repeat 9. 1 <= k <= len(nums) <= 100,000, and each value is from 1 to 100,000.

Starter code

class Solution:
    def maximumSubarraySum(self, nums, k):
        pass

Public examples

  1. nums = [1, 5, 4, 2, 9, 9, 9], k = 3gives15
  2. nums = [1, 2, 9], k = 2gives11
  3. nums = [4, 7, 2], k = 1gives7

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.