Prefix Sum 2 Finding the maximum occurrence of an element in ranges / Frequency problem
import java.util.ArrayList;
public class PrefixSum2 {
// Maximum appearing element in given ranges
public static int getMaxOccurence(int[] L, int[] R) {
int n = L.length;
int[] array = new int[1000];
for(int i = 0; i < n; i++) {
array[L[i]]++;
array[R[i] + 1]--;
}
int max = array[0];
int res = 0;
for(int i = 1; i < 1000; i++) {
array[i] += array[i-1];
if(array[i] > max){
max = array[i];
res = i;
}
}
return res;
}
public static void main(String[] args) {
int[] L = {1,2,5,15};
int[] R = {5,8,7,18};
System.out.println(getMaxOccurence(L, R));
}
}
Comments
Post a Comment