Interview Question
Software Engineer / DevelopersAccording to the problem statement its the difference between any two numbers with the smaller number appearing after the larger number.
Thus for your example the answer must be [9-2] 7
Hi,
also we can solve by taking the smallest and biggest element in the array, and the max difference would be answer
O(n) solution
public void MaximumDifferenceBetweenTwoElements()
{
//The function assumes that there are at least two
//elements in array.
//The function returns a negative value if the array is
//sorted in decreasing order.
//Returns 0 if elements are equal
//We take difference between the picked element and the minimum element found so far.
//So we need to keep track of 2 things:
//1) Maximum difference found so far (max_diff).
//2) Minimum number visited so far (min_element).
int [] arr = {2, 3, 10, 6, 4, 8, 1};
int maxDiff = arr[1] - arr[0];
int minElement = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] - minElement > maxDiff)
maxDiff = arr[i] - minElement;
if (arr[i] < minElement)
minElement = arr[i];
}
Console.WriteLine(maxDiff);
}
Here is a O(n) solution.
- lyzoridc April 09, 2010