Skip to content

A divide and conquer method in finding the maximum difference pair #3692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions divide_and_conquer/max_difference_pair.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from typing import List


def max_difference(a: List[int]) -> (int, int):
"""
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, 1, 7, 9, 0, 7])
(1, 9)
"""
# base case
if len(a) == 1:
return a[0], a[0]
else:
# split A into half.
first = a[: len(a) // 2]
second = a[len(a) // 2 :]

# 2 sub problems, 1/2 of original size.
small1, big1 = max_difference(first)
small2, big2 = max_difference(second)

# get min of first and max of second
# linear time
min_first = min(first)
max_second = max(second)

# 3 cases, either (small1, big1),
# (min_first, max_second), (small2, big2)
# constant comparisons
if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:
return small2, big2
elif big1 - small1 > max_second - min_first:
return small1, big1
else:
return min_first, max_second


if __name__ == "__main__":
import doctest

doctest.testmod()