Q-7 PepCoding | Largest Subarray With Contiguous Elements
Mon Jan 23 2023 11:12:05 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
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));
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/largest-subarray-with-contiguous-elements-official/ojquestion
Comments