Interview Question
Country: India
Here is the code. Please correct me if any mistake
void FindMaxDiff(int arr[], int arr_size)
{
int i, first, second;
int diff = 0;
/* There should be atleast two elements*/
if(arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = 0;
for(i = 0; i < arr_size ; i ++)
{
/*If current element is smaller than first then update both first and second */
if(arr[i] > first)
{
second = first;
first = arr[i];
if(diff < (first-second))
diff = (first-second);
}
/* If arr[i] is in between first and second then update second */
else if (arr[i] > second)
{
second = arr[i];
}
}
Printf(“ xxxx “);
}
int maxDiff( int* numbers, int size ) {
int max_diff = 0;
int min_ind = 0;
for( int i = 0 ; i < size; i++ ) {
if( numbers[i] < numbers[min_ind] ) {
min_ind = i;
}
else {
if ( ( numbers[i] - numbers[min_ind] ) > max_diff ) {
max_diff = numbers[i] - numbers[min_ind] ;
}
}
}
return max_diff;
}
Simply find smallest and largest element in the array. ie answere
- tomb February 18, 2012