用 Python 编写程序,从两个数字列表中查找最大距离对

pythonserver side programmingprogramming

假设我们有两个数字列表,分别称为 A 和 B,它们的长度相同。我们必须找到所有 0 ≤ i < j < n 的最大值:|a[i] - a[j]| + |b[i] - b[j]| + |i - j|

因此,如果输入为 A = [2, 4, 10, 6] B = [3, 4, 7, 5],则输出将为 14,因为当 i = 0 且 j = 2 时,我们得到 |2 - 10| + |3 - 7| + |1 - 3|。

为了解决这个问题,我们将遵循以下步骤 −

  • ans := 0
  • n := a 的大小
  • 对于 [(-1, -1) ,(-1, 1) ,(1, -1) ,(1, 1) ] 中的每个对 (s, t),执行
    • cur_min := 无穷大
    • cur_max := -无穷大
    • 对于 0 到 n 范围内的 i,执行
      • tmp := s * a[i] + t * b[i] + i
      • cur_min := cur_min 的最小值,tmp
      • cur_max := cur_max 的最大值, tmp
    • ans := ans 的最大值,(cur_max - cur_min)
  • 返回 ans

让我们看看下面的实现以便更好地理解 −

示例

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))

输入

[2, 4, 10, 6],[3, 4, 7, 5]

输出

14

相关文章


有用资源