During an interview, I've been asked the following Question:
You're given an array of integer numbers.
Find the maximum difference between two elements
arr[j] - arr[i]for any sub array in the array, so thatj>i.For example:
array =
{20,18,45,78,3,65,55}, max diff is65 - 3 = 62.array =
{20,8,45,78,3,65,55}, max diff is78 - 8 = 70.
Here is the solution I come up with:
private static int calculateProfit() {
int[] arr = {20, 18, 45, 78, 3, 65, 55};
int maxProfit = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length - 1; j > 0; j--) {
if (arr[i] < arr[j] && i < j) {
maxProfit = Math.max(arr[j] - arr[i], maxProfit);
}
}
}
return maxProfit; // ans: (65 - 3) = 62
}
The problem is that it runs in O(n^2). How it can be done with a better time complexity?
This problem can be solved in a linear time O(n), with a single run through the given array.
We need to declare only a couple of local variables, no data additional data structures required, space complexity is O(1).
These are the variables we need to track:
min- the lowest value encountered so far;max- the highest encountered value;maxProfit- maximal profit that can be achieved at the moment.While declaring these variables, we can either initialize
mintoInteger.MAX_VALUEandmaxtoInteger.MIN_VALUE, or initialize both with the value of the first element in the array (this element should be present because the array needs to have at least two elements, otherwise the task has no sense).And here is a couple of caveats:
Since
maxelement can not precede theminelement, when a newminelement is encountered (when the current element is less thanmin) themaxelement also needs to be reinitialized (withInteger.MIN_VALUEor with the value of the current element depending on the strategy you've chosen at the beginning).maxProfitshould be checked against the difference betweenmaxandmineach time when a newmaxhas been encountered.That's how it might be implemented:
main()Output: