Ninja has an integer array 'A' of 'N' elements. He is allowed to perform at most 'X' operations on the array.
In one operation he can increment any one element of the array by 1. An operation can be performed repeatedly on the same element.
He wants to know the longest subarray he can obtain in which all the elements of the subarray are equal.
A subarray is a contiguous part of an array.
Example :‘N’ = '7'
'X' = 5
The following line contains 'Ai', the 'ith' element from the left.
3 4 8 5 9 6 1
Assuming 0-based indexing, Ninja can perform the operations on 'i'=2, 'A[i]' = 8 once and 'i'=3, 'A[i]' = 5 four times to obtain [3 4 9 9 9 6 1].
Thus, the longest subarray with equal elements that can be obtained is [9, 9, 9] i.e. of length 3.
The first line contains an integer 'T', which denotes the number of test cases to be run. Then the test cases follow.
The first line of each test case contains two space-separated integers 'N' and 'X', denoting the total number of elements and the maximum number of allowed operations respectively.
The second line of each test case contains 'N' space-separated integers, the elements of the array 'A'.
Output format :
For each test case, return the length of the longest subarray with the same elements that could be obtained after performing the operations.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
0 <= X < 2^31
1 <= Ai <= 10^9 (0 <= i <= N-1)
The sum of 'N' overall 'T' does not exceed 10^5.
Time Limit: 1 sec
2
4 2
1 1 2 3
3 0
2 3 4
3
1
For test case 1:
Ninja can apply the operation once on A[0] and A[1] to get [2,2,2,3]. Hence, the longest subarray with all elements as the same is A[0:2] i.e. length 3.
For test case 2:
Since all elements are distinct and 'X' = 0 i.e. no operation is allowed. The longest subarray is only a single element.
2
8 5
1 3 2 2 1 3 4 2
5 3
1 2 1 1 1
5
4
If we can obtain a length 'Y' satisfying the condition, can we obtain a length of 'Y-1'?
Approach :
Algorithm:
O(N*log N)
Since we are binary searching, the time complexity of binary search is of the order O(log N) and the checker function traverses the entire array 'A' once, hence the time complexity is of the order O ( N log N ).
O(N)
Since we will be using a deque to find and maintain a sliding window maximum, the space complexity is of the order O(N).