This question seemed really interesting to me, now I don't know whether my approach is perfectly correct or not, but I gave it a try and it gives me correct result for the current input.
So according to my approach, I keep one segment tree to keep max values for all the ranges and another segment tree that stores the value for difference between the max of left side - max of right side.
Point to be noted here, why I am doing so is because we need A[i] - A[j] and i <= j, so if we keep on storing max of left range - max of right range, then we will always end up having the difference value and also i <= j.
Have a look at my code, to understand this more.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5; // limit for array size
int n; // array size
int t[2 * N];
int t_ans[2*N];
void build1() { // build the tree
for (int i = n - 1; i > 0; --i) t[i] = max(t[i<<1],t[i<<1|1]);
}
void build2() { // build the tree
for (int i = n - 1; i > 0; --i) t_ans[i] = t[i<<1] - t[i<<1|1];
}
void modify(int p, int value) { // set value at position p
for (t[p += n] = value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1];
}
int query(int l, int r) { // sum on interval [l, r)
int res = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l&1) res = max(res,t[l++]);
if (r&1) res = max(res,t[--r]);
}
return res;
}
int query2(int l, int r) { // sum on interval [l, r)
int res = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l&1) res = max(res, t_ans[l++]);
if (r&1) res = max(res, t_ans[--r]);
}
return res;
}
int main() {
cin>>n;
for (int i = 0; i < n; ++i) {
scanf("%d", t + n + i);
}
build1();
build2();
/*
For testing purpose only
for(int i=0; i<2*n; i++) {
cout<<t[i]<<" ";
}
cout<<endl;
for(int i=0; i<2*n; i++) {
cout<<t_ans[i]<<" ";
}
cout<<endl;
*/
int q;
cin>>q;
for(int i=0; i<q; i++) {
int l,r;
cin>>l>>r;
cout<<query2(l,r+1)<<endl;
}
return 0;
}
I am keeping two segment trees, one tree for storing max range values and it's called t and another that stores max of difference and that is being stored in t_ans.
Now I call two different build methods, build1() builds segment tree for max values and build2() builds segment tree for difference between max of left tree - max of right tree.
Let me know if I made any error or mistakes in my current approach.
Hope this helps!