ADP Interview Question
Developer Program EngineersCountry: India
Interview Type: Phone Interview
The question is phrased very strangely; I have no idea what input 2 does and where 2MHz came from, but let's assume we have an array of integers and we want to find the max positive difference across two selections. The easiest way is to sort then
((last - first)) + ((last-1) - (first+1))
int selection1 = -1;
int selection2 = -2;
//Since the array is sorted, we don't need to check if the subtraction operation is +ve (incase of -ve values being allowed)
selection1 = A[A.length-1] - A[0];
selection2 = A[A.length-2] - A[1];
maxDifference = selection1 + selection2;
Insertion sort if the array is very small, mergesort otherwise = O(nlgn)
Comparison operation twice 2 * C
O(nlogn) + 2C
public int findMaxPositiveFrequency (int [] frequency){
- Anonymous August 14, 2015int [] left = new int [frequency.length] ;
int max = 0 , min_so_far = frequency[0] ;
for (int i = 1 ; i < frequency.length ; ++i) {
if (frequency[i] < min_so_far) {
left[i] = max ;
min_so_far = frequency[i] ;
} else {
max = Math.max(max, frequency[i] - min_so_far) ;
left[i] = max ;
}
}
int [] right = new int [frequency.length] ;
max = 0 ;
int max_so_far = frequency[frequency.length - 1] ;
for (int i = frequency.length -2 ; i >= 0 ; --i) {
if (frequency[i] > max_so_far) {
right[i] = max ;
max_so_far = frequency[i] ;
} else {
max = Math.max(max, max_so_far - frequency[i]) ;
right[i] = max ;
}
}
max = 0 ;
for (int i = 0 ; i < frequency.length ; ++i) {
max = Math.max(max, left[i] + right[i]) ;
}
return max ;
}