arraysalgorithmarray-algorithms

Find the largest difference in every subarray [i, j]


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.


Solution

  • 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

    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;
    }