MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / max_difference

Function max_difference

divide_and_conquer/max_difference_pair.py:1–38  ·  view source on GitHub ↗

We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2,

(a: list[int])

Source from the content-addressed store, hash-verified

1def max_difference(a: list[int]) -> tuple[int, int]:
2 """
3 We are given an array A[1..n] of integers, n >= 1. We want to
4 find a pair of indices (i, j) such that
5 1 <= i <= j <= n and A[j] - A[i] is as large as possible.
6
7 Explanation:
8 https://www.geeksforgeeks.org/maximum-difference-between-two-elements/
9
10 >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7])
11 (1, 9)
12 """
13 # base case
14 if len(a) == 1:
15 return a[0], a[0]
16 else:
17 # split A into half.
18 first = a[: len(a) // 2]
19 second = a[len(a) // 2 :]
20
21 # 2 sub problems, 1/2 of original size.
22 small1, big1 = max_difference(first)
23 small2, big2 = max_difference(second)
24
25 # get min of first and max of second
26 # linear time
27 min_first = min(first)
28 max_second = max(second)
29
30 # 3 cases, either (small1, big1),
31 # (min_first, max_second), (small2, big2)
32 # constant comparisons
33 if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:
34 return small2, big2
35 elif big1 - small1 > max_second - min_first:
36 return small1, big1
37 else:
38 return min_first, max_second
39
40
41if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected