Interview Question
Country: United States
void GetMaxNumberAndOccurance(int a[], int *maxNumber, int *Occurance)
{
*maxNumber=a[0];
*Occurance=1;
for(int i=1;i<10;i++)
{
if(a[i] > *maxNumber)
{
*maxNumber =a[i];
*Occurance = 1;
}
else if(a[i] == *maxNumber) *Occurance = *Occurance+1;
}
}
int main()
{
int a[10]={1,5,3,4,2,4,5,2,5,2};
int x,y;
GetMaxNumberAndOccurance(a,&x,&y);
printf("%d %d",x,y);
return 0;
}
You can do it in one pass.
- Anonymous March 06, 2012Do the normal algorithm for the max, but also maintain the frequency of the current maximum. If the current maximum changes, reset the frequency.