input: from typing import List
  from collections import defaultdict
  
  def max_subarray_sum_with_diff(nums: List[int], k: int) -> int:
      """
      Given an array nums of length n and a positive integer k.
  
      A subarray of nums is considered valid if the absolute difference between its first and last element is exactly k, i.e., the subarray nums[i..j] is valid if |nums[i] - nums[j]| == k.
  
      Return the maximum sum of a valid subarray of nums. If there are no valid 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:     
      max_sum = 0
      n = len(nums)
      
      for i in range(n):
          for j in range(i + 1, n):
              if abs(nums[i] - nums[j]) == k:
                  subarray_sum = sum(nums[i:j+1])
                  max_sum = max(max_sum, subarray_sum)
  
      return max_sum
  