Suppose we have two list of numbers called A and B, and their lengths are same. We have to find the maximum value for all 0 ≤ i < j < n: |a[i] - a[j]| + |b[i] - b[j]| + |i - j|
So, if the input is like A = [2, 4, 10, 6] B = [3, 4, 7, 5], then the output will be 14, as when i = 0 and j = 2 and we get |2 - 10| + |3 - 7| + |1 - 3|.
To solve this, we will follow these steps −
- ans := 0
- n := size of a
- for each pair (s, t) in [(-1, -1) ,(-1, 1) ,(1, -1) ,(1, 1) ], do
- cur_min := infinity
- cur_max := -infinity
- for i in range 0 to n, do
- tmp := s * a[i] + t * b[i] + i
- cur_min := minimum of cur_min, tmp
- cur_max := maximum of cur_max, tmp
- ans := maximum of ans, (cur_max - cur_min)
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, a, b): ans = 0 n = len(a) for s, t in [(-1, -1), (-1, 1), (1, -1), (1, 1)]: cur_min = float("inf") cur_max = float("-inf") for i in range(n): tmp = s * a[i] + t * b[i] + i cur_min = min(cur_min, tmp) cur_max = max(cur_max, tmp) ans = max(ans, cur_max - cur_min) return ans ob = Solution() A = [2, 4, 10, 6] B = [3, 4, 7, 5] print(ob.solve(A, B))
Input
[2, 4, 10, 6],[3, 4, 7, 5]
Output
14