input: from typing import List
  from collections import defaultdict
  
  def max_subarray_sum(nums: List[int], k: int) -> int:
      """
      You are given an array nums of length n and a positive integer k.
  
      A subarray of nums is called good if the absolute difference between its first and last element is exactly k, in other words, the subarray nums[i..j] is good if |nums[i] - nums[j]| == k.
  
      Return the maximum sum of a good subarray of nums. If there are no good subarrays, return 0.
  
      Examples:
      >>> nums = [1,2,3,4,5,6], k = 1
      11
      >>> nums = [-1,3,2,4,5], k = 3
      11
      >>> nums = [-1,-2,-3,-4], k = 2
      -6
  
      Constraints:
      2 <= nums.length <= 10^5
      -10^9 <= nums[i] <= 10^9
      1 <= k <= 10^9
      """
  
output: 
      num_indices = defaultdict(list)
      for i, num in enumerate(nums):
          num_indices[num].append(i)
  
      max_sum = 0
      for num in num_indices:
          if num + k in num_indices:
              for i in num_indices[num]:
                  for j in num_indices[num + k]:
                      if i < j:
                          subarray_sum = sum(nums[i:j+1])
                          max_sum = max(max_sum, subarray_sum)
          if num - k in num_indices:
              for i in num_indices[num]:
                  for j in num_indices[num - k]:
                      if i < j:
                          subarray_sum = sum(nums[i:j+1])
                          max_sum = max(max_sum, subarray_sum)
  
      return max_sum
  