See the original problem on HackerRank.
You are given a sequence of integers
S, your task is to find a pair
i,j of indices with
i<j that maximizes the difference
Note that what makes this challenge more interesting is the requirement of order, that i < j (without it you simply need to find the maximum and minimum element of S).
You have to output the value of the maximum difference.
N followed by
N space separated integers
S[i] on a new line.
The maximum difference as an integer.
This problem has a naive quadratic solution that involves considering every pairs \(i,j\) with \(j>i\) and tracking the maximum. What makes this naive is that it is a bruce force solution that does not consider the input domain or the structure of the problem.
To see the solution, consider what pairs we should consider for the index \(j\). Let’s suppose that \(j\) is the right hand index so we need only look at elements of \(S\) that precede \(j\). The difference \(s[j]-s[i]\) is maximized for the index \(i\) that contains the minimum element of \(s,…s[j-1]\).
Therefore, instead of looking over pairs, we need only to keep track of the maximum element preceding any other index. This is linear.
Here is a possible C++ implementation of the described idea:
The solution above hides two emerging patterns:
- we calculate a running minimum (
minis updated independently at every step)
- we reduce to the max value on the difference between the current element and the current running minimum
Here is an implementation:
From C++20, ranges’s
view::partial_sum can help remove the support array:
It should be clear that
mins is a lazy range and not a
vector. The entire chain is lazy so the algorithm is one-pass.
Another solution - less efficent and for some people preparatory for the previous solution - consists in using two prefix sums:
Just for fun, an alternative solution is based on the Maximum Subarray Sum problem. We first calculate the differences between adjacent elements and then solve the maximum subarray problem on the resulting array.
In C++ we can combine several standard algorithms: