Harmonious Interval

Time limit: 2.0 sec
Memory limit: 256 MB

Problem Statement

In the kingdom of Melodia, the royal composer seeks the secret to a perfect symphony. Legend has it that a contiguous sequence of notes, when arranged in the correct order, creates an interval of perfect harmony. Specifically, a sequence of frequencies is said to be harmonious if the difference between its maximum and minimum frequency is exactly $k$. The composer has been handed a mysterious sequence of frequencies by a wandering minstrel, and he now tasks you with deciphering the length of the longest harmonious interval hidden within. Your task is to help the composer by determining the length of the longest contiguous subarray of frequencies such that the difference between the maximum and minimum values in the subarray is exactly $k$. If no such subarray exists, output $-1$. ## Input Format - The first line of input contains two space-separated integers: - $n$, the number of frequencies in the sequence, and - $k$, the required harmonious difference. - The second line contains $n$ space-separated integers representing the sequence of frequencies. ## Output Format Print a single integer representing the length of the longest contiguous subarray for which $$\text{max(subarray)} - \text{min(subarray)} = k.$$ If no such subarray exists, output $-1$. ## Examples #### Input 5 3 1 3 6 4 1 #### Output 3 #### Input 4 5 2 2 2 2 #### Output -1

Code Editor

Language:
Theme: