I have an array p
with integers .
I need to compute d[i, j] for all (i, j) : i<j
, where :
d[i, j] = max (p[b] - p[a]) , i<=a<b<=j
I know how to solve this for d[1,n]
in O(n) . But for every pair ? Here's my thoughts:
right = j
left = i
mx = p[j]
mn = p[i]
while(left < right):
if(p[right] > mx)
mx = p[right]
if(p[left] < mn)
mn = p[left]
right--; left ++;
return (mx-mn)
Now I can repeat for every pair : #pairs = n^2 and therefore O(n^3).
But there must be something faster.
d[i, j] = p[m] - p[l]
then d[a, b] = d[i, j] for all a <= m < l <=b
(basically the [l, m] is contained in [a, b])T(n) = Ω(n^2)
We can compute d[i, j] = max (p[b] - p[a]) , i<=a<b<=j
for a fixed i
in linear time i.e, O(n)
. How?
Let us say that we have a array called values
of size n
startIndex
). This is same as fixing i
startIndex
to end of the array
minValue
) and also the maximum difference(maxDiff
) encountered so farendIndex
, the largest possible difference in the range [startIndex,endIndex]
is just max(maxDiff, values[endIndex] - minValue)
If we repeat the above approach for each index by fixing it as the startIndex
, then we can compute largest possible difference for all the sub-arrays of any given array in O(n^2)
// implementation of above approach in C++
vector<vector<int>> findLargestDiff(vector<int>& values) {
int n = values.size();
vector<vector<int>> largestDiff(n, vector<int>(n));
for (int startIndex = 0; startIndex < n; startIndex++) {
int minValue = values[startIndex];
int maxDiff = 0;
for (int endIndex = startIndex; endIndex < n; endIndex++) {
minValue = min(minValue, values[endIndex]);
maxDiff = max(maxDiff, values[endIndex] - minValue);
largestDiff[startIndex][endIndex] = maxDiff;
}
}
return largestDiff;
}