import java.util.*;
public class Main {
public static int solution(int[] arr) {
int length = 0;
for(int i = 0 ; i < arr.length ; i++){
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
//HS to check duplicacy
HashSet<Integer> set = new HashSet<>();
for(int j =i ; j < arr.length ;j++ ){
max = Math.max(arr[j],max);
min = Math.min(arr[j],min);
if(set.contains(arr[j])) break;
set.add(arr[j]);
//contiguous element trick
int val1 = max - min;
int val2 = j-i;
if(val1 == val2){
int potential = j -i +1;
if(length < potential)
length = potential;
}
//if max - min becomes more than no.of indexes break;
if(val1 > arr.length)break;
}
}
return length;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] arr = new int[scn.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
System.out.println(solution(arr));
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter