forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximum Absolute Difference
47 lines (39 loc) · 1.25 KB
/
Maximum Absolute Difference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N.
f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.
For example,
A=[1, 3, -1]
f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5
So, we return 5.*/
//this one is 0(n^2) solution
int f_max = 0;
for(int i=0 ;i< A.size() ; i++){
for(int j=i+1 ; j<A.size() ; j++){
int f = abs(A[i]-A[j])+(j-i);
if(f > f_max) f_max = f;
}
}
return f_max;
//this one is 0(n) solution
int Solution::maxArr(vector<int> &A) {
int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN, max4 = INT_MIN;
int ans = INT_MIN;
int size = A.size();
for (auto i = 0; i<size; ++i)
{
max1 = max(max1, A[i] + i);
max2 = max(max2, -A[i] + i);
max3 = max(max3, A[i] - i);
max4 = max(max4, -A[i] - i);
}
for (auto i = 0; i<size; ++i)
{
ans = max(ans, max1 - A[i] - i);
ans = max(ans, max2 + A[i] - i);
ans = max(ans, max3 - A[i] + i);
ans = max(ans, max4 + A[i] + i);
}
return ans;
}