[Geeks for Geeks] Maximum absolute difference between sum of two contiguous sub-arrays

Maximum absolute difference between sum of two contiguous sub-arrays

Given an array of integers, find two non-overlapping contiguous sub-arrays such that the absolute difference between the sum of two sub-arrays is maximum.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int findMaxAbsDiff(vector<int> A) {
int n = A.size();
vector<int> midp(n), madp(n);
midp[n-1] = madp[n-1] = A[n-1];
for(int i = n - 2, mi = A[n-1], ma = A[n-1]; i >= 0; i--) {
mi = min(A[i], mi + A[i]);
ma = max(A[i], ma + A[i]);
midp[i] = mi;
madp[i] = ma;
}
int res = 0;
for(int i = 0, mi = 0, ma = 0; i < n - 1; i++) {
mi = min(A[i], mi + A[i]);
ma = max(A[i], ma + A[i]);
res = max({res,
abs(mi - midp[i+1]),
abs(mi - madp[i+1]),
abs(ma - midp[i+1]),
abs(ma - madp[i+1])
});
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/maximum-absolute-difference-between-sum-of-two-contiguous-sub-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.