#C8854. Maximum Value After Limited Swaps

    ID: 52882 Type: Default 1000ms 256MiB

Maximum Value After Limited Swaps

Maximum Value After Limited Swaps

Problem Statement

You are given an integer t representing the number of test cases. For each test case, you are provided with an array of n integers and an integer d which represents the maximum allowed difference between two integers to perform a valid swap.

You are allowed to repeatedly swap adjacent elements in the sorted version of the array if the difference between them is less than or equal to d. More specifically, if you have a chain of numbers in the sorted array where every consecutive pair has a difference less than or equal to d, then by repeatedly swapping, these elements can be rearranged arbitrarily among themselves. Your task is to determine the maximum possible value from such a chain that can be brought to the desired position. In practice, after sorting the array in non‐decreasing order, starting from the largest element, traverse backwards while the difference between the current maximum and the preceding element is at most d. Stop when the condition fails, and output the current maximum value found in this contiguous chain.

Note:

  • If no valid swap can be made (i.e. d is 0 or the differences are too large), the answer will simply be the largest element of the array.
  • The input is read from stdin and the output should be printed to stdout, with one result per test case on a new line.

inputFormat

Input Format

The first line contains an integer t, the number of test cases.

Each test case consists of two lines:

  • The first line contains two space-separated integers n and d — the number of elements in the array and the maximum allowed difference for a valid swap.
  • The second line contains n space-separated integers representing the elements of the array.

outputFormat

Output Format

For each test case, print the maximum possible value (an integer) that can be obtained after performing the allowed swaps, each on a new line.

## sample
3
5 2
3 6 7 8 10
4 1
1 1 1 1
6 5
1 5 9 12 8 7
10

1 12

</p>