I am solving questions on arrays from here.
Problem: 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.
Solution approach:
|A[i] - A[j]| + |i - j| gives us 4 cases:
Case1:|A[i] - A[j]| + |i - j| = -A[i]+ A[j] - i + j = -(A[i]+ i) + ( A[j] + j) Case2:|A[i] - A[j]| + |i - j| = -A[i]+ A[j] + i - j = -(A[i] - i) + (A[j]-j) Case3:|A[i] - A[j]| + |i - j| = A[i]- A[j] - i + j = (A[i] - i) - (A[j] -j) Case4:|A[i] - A[j]| + |i - j| = A[i]- A[j] + i - j = (A[i] + i) - (A[j] + j)
Cases 1 and 4 are equivalent and can be find as the difference between the max and min value of A[i]+i
Cases 2 and 3 are equivalent and can be find as the difference between the max and min value of A[i]-i
How can I perfect this code?
def max_abs_diff(array):
""" returns sum of absolute difference of values and corresponding indices of an array"""
max1=[]#array to store maximum values given by A[i] + i
min1=[]#array to store minimum values given by A[i] + i
max2=[]#array to store maximum values given by A[i] - i
min2=[]#array to store minimum values given by A[i] - i
for i, elem in enumerate(array):
max1.append(elem + i)
min1.append(elem + i)
max2.append(elem - i)
min2.append(elem - i)
return max(max(max1) - min(min1) , max(max2)-min(min2))
Test cases:
print max_abs_diff([2,2,2]) == (2)
print max_abs_diff([2,-2,2])== (5)
print max_abs_diff([-4,-2,-3,-4,-5]) == (6)
print max_abs_diff([-1]) == (0)
print max_abs_diff([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (18)
print max_abs_diff( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (20)
print max_abs_diff([-5, -2, -1, -4, -7]) == (8)