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.
My solutions:
A = [-70, -64, -6, -56, 64, 61, -57, 16, 48, -98]
def maxArr(A):
size = len(A)
max_diff = 0
start = 0
end = 1
while start < size:
a1 = abs(A[start] - A[end])
b1 = abs((start + 1) - (end + 1))
abs_num = a1 + b1
max_diff = max(max_diff, abs_num)
if end < size - 1:
end += 1
else:
start += 1
end = 1
return max_diff
print(maxArr(A))
This is my solution, but I failed to optimize my time complexity:
Best time complexity is O(N).
Good solutions:
https://www.geeksforgeeks.org/maximum-absolute-difference-value-index-sums/
'DataStructure > Array' 카테고리의 다른 글
Best Time to Buy and Sell Stock II (0) | 2018.10.29 |
---|---|
Remove Duplicates from Sorted Array (0) | 2018.10.22 |
Max Sum Contiguous Subarray (0) | 2018.10.16 |
Add One To Number (0) | 2018.10.15 |
Min Steps in Infinite Grid (0) | 2018.10.15 |