values and a positive integer gap.
Call a contiguous segment values[i..j] (with i < j) fitting if its two end elements differ by exactly gap: |values[i] - values[j]| == gap.
Return the largest element sum over all fitting segments. If no segment fits, return 0.
The sum may turn out negative.values=[3, -2, 8, 6, 1], gap=5 → 9
Two segments qualify: [3, -2, 8] (|3 − 8| = 5, sum 9) and [6, 1] (|6 − 1| = 5, sum 7). The best sum is 9.
values=[4, 4, 4], gap=2 → 0
All elements are equal, so the ends always differ by 0. No segment qualifies, and the answer is 0.
values=[-5, -9, -2, -7], gap=4 → -14
values=[3, -2, 8, 6, 1], gap=5
9
Run checks the first 3 tests in your browser. Submit checks all 104 tests on the server, hidden ones included.