Skip to content

Commit 73e89e8

Browse files
choyinyshermanhui
authored andcommitted
Add a divide and conquer method in finding the maximum difference pair (TheAlgorithms#3692)
* A divide and conquer method in finding the maximum difference pair * fix formatting issues * fix formatting issues * add doctest runner
1 parent e898f0a commit 73e89e8

File tree

1 file changed

+47
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)