GeeksforGeeks » Interview Questions
Interview Question for Software Engineer/Developer (Fresher) about Arrays
(3 posts)-
given an unsorted array, find the elements which have the maximum difference in O(n) time
-
It means we have to find out the smallest and largests elements , it can be done in o(n)
-
#include<stdio.h> #include<conio.h> int findMaxDifference(int testArray[],int size); int main() { int testArray[]={3,1,5,7,9,12,6}; int size=(sizeof(testArray)/sizeof(testArray[0])); int maxDifference; maxDifference=findMaxDifference(testArray,size); printf("Maximum Difference in the Given array is %d ",maxDifference); getch(); return 0; } int findMaxDifference(int a[],int size) { int smallest,largest,smallIndex=0,largeIndex=0; int i; largest=smallest=a[0]; for(i=1;i<size;i++) { if(a[i]>largest) { largest=a[i]; largeIndex=i; } else if(a[i]<smallest) { smallest=a[i]; smallIndex=i; } } printf("The elements with largest differnece are %d %d \n",a[smallIndex],a[largeIndex]); printf("The index of largest and smallest elemnt in the array is %d %d \n",largeIndex,smallIndex); return (largest-smallest); }
Reply
You must log in to post.