ADP Interview Question
Developer Program EngineersCountry: United States
Interview Type: In-Person
brilliant code , can you explain your approach please ? I mean what was thee intuition behind the logic ?
public class FindMaxFreq {
public static void main(String[] args) {
int arr[] = {2,30,15,10,8,25,80};
findTopTwoFreqDiff(arr);
}
public static void findTopTwoFreqDiff(int arr[])
{
int tempArr[] = new int[arr.length];
tempArr[0] = 0;
for (int i=1; i < arr.length; i++)
{
for (int j=0; j < i ; j++)
{
if (arr[i]> arr[j])
{
tempArr[i] = tempArr[j] + arr[i]-arr[j];
}
else
{
tempArr[i]=0;
}
}
}
int firstMax;
int secondMax;
if (tempArr[0] > tempArr[1])
{
firstMax = tempArr[0];
secondMax = tempArr[1];
}
else
{
firstMax = tempArr[1];
secondMax = tempArr[0];
}
for(int i=2; i< tempArr.length; i++)
{
if (firstMax < tempArr[i])
{
secondMax = firstMax;
firstMax = tempArr[i];
}
else
{
secondMax = Math.max(secondMax, tempArr[i]);
}
}
System.out.println("First Max :" + firstMax + " second max :"+ secondMax);
System.out.println("Max Frequency = " + (firstMax + secondMax) );
}
}
Hi , Guys
Can any body tell me what is the problem with below code as its working fine for most of the test cases but not for all..:(
import java.util.Arrays;
public class PositiveFrequencyFinder {
public static int maximumPositiveFrequency(int[] input1,int input2)
{
//creating new array for storing all positive frequency difference
int positiveFreqDiff[] = new int[input2];
boolean isFreqDiffPositive = false;
int freqSum = 0, j = 0, i = 0;
do {
if (i < (input2 - 1) && input1[i + 1] > input1[i]) {
isFreqDiffPositive = true;
freqSum = freqSum + (input1[i + 1] - input1[i]);
continue;
} else {
if (isFreqDiffPositive) {
positiveFreqDiff[j++] = freqSum;
}
freqSum = 0;
}
}
while (i++ < (input2 - 1));
Arrays.sort(positiveFreqDiff);
return (positiveFreqDiff[input2 - 1] + positiveFreqDiff[input2 - 2]);
}
public static void main(String[] args) {
int input1[]={2,30,15,10,8,25,80};
System.out.println("maximumPositiveFrequency(input1, 7)"+maximumPositiveFrequency(input1, 7));
}
}
two pass solution
first from left to right , then right to left
- Scott August 11, 2015