input: from typing import List
  from collections import defaultdict
  
  def find_optimal_subarray(nums: List[int], k: int) -> int:
      """
      Given an array nums and a positive integer k, find the maximum sum of any subarray where the absolute difference between the first and last elements is exactly k. If no such subarray exists, 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 <= len(nums) <= 10^5
      -10^9 <= nums[i] <= 10^9
      1 <= k <= 10^9
      """
output:     start_indices = defaultdict(list)
      max_sum = 0
      
      for i, num in enumerate(nums):
          start_indices[num].append(i)
      
      for i, num in enumerate(nums):
          if num - k in start_indices:
              for start_index in start_indices[num - k]:
                  if start_index <= i:
                      max_sum = max(max_sum, sum(nums[start_index:i+1]))
                      
          if num + k in start_indices:
              for start_index in start_indices[num + k]:
                  if start_index <= i:
                      max_sum = max(max_sum, sum(nums[start_index:i+1]))
                      
      return max_sum