Skip to content

Commit 03d310a

Browse files
committed
Maximum Absolute Difference
1 parent 31b6f9e commit 03d310a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/maximum-absolute-difference/
3+
4+
You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j)
5+
for all 1 ≤ i, j ≤ N.
6+
f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.
7+
8+
For example,
9+
A=[1, 3, -1]
10+
f(1, 1) = f(2, 2) = f(3, 3) = 0
11+
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
12+
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
13+
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5
14+
So, we return 5.
15+
"""
16+
class Solution:
17+
# @param A : list of integers
18+
# @return an integer
19+
def maxArr(self, A):
20+
min_pair1 = min_pair2 = float('inf')
21+
max_pair1 = max_pair2 = float('-inf')
22+
for i in range(len(A)):
23+
min_pair1 = min(min_pair1, A[i] + i)
24+
max_pair1 = max(max_pair1, A[i] + i)
25+
26+
min_pair2 = min(min_pair2, A[i] - i)
27+
max_pair2 = max(max_pair2, A[i] - i)
28+
29+
return max(max_pair1 - min_pair1, max_pair2 - min_pair2)

0 commit comments

Comments
 (0)