|
| 1 | +""" |
| 2 | +The Max-Min Problem is finding the maximum and minimum value in an array. |
| 3 | +
|
| 4 | +This is a divide and conquer approach to solve the Max-Min Problem. |
| 5 | +
|
| 6 | +For more information: |
| 7 | +https://www.tutorialspoint.com/data_structures_algorithms/max_min_problem.htm |
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +class Pair: |
| 12 | + """ |
| 13 | + Structure to store both maximum and minimum elements |
| 14 | + """ |
| 15 | + |
| 16 | + def __init__(self): |
| 17 | + self.max = 0 |
| 18 | + self.min = 0 |
| 19 | + |
| 20 | + |
| 21 | +def max_min_divide_conquer(arr: list, low: int, high: int) -> "Pair": |
| 22 | + """ |
| 23 | + Returns the maximum and minimum elements in the array. |
| 24 | +
|
| 25 | + Args: |
| 26 | + arr: A list of integers |
| 27 | + low: An integer representing the start index of the array |
| 28 | + high: An integer representing the end index of the array |
| 29 | +
|
| 30 | + Returns: |
| 31 | + A Pair object containing the maximum and minimum elements in the array |
| 32 | +
|
| 33 | + >>> arr = [1, 3, 4, 2, 8, 9, 7, 6, 5] |
| 34 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).max |
| 35 | + 9 |
| 36 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).min |
| 37 | + 1 |
| 38 | + >>> arr = [7] |
| 39 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).max |
| 40 | + 7 |
| 41 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).min |
| 42 | + 7 |
| 43 | + >>> arr = [7, 1] |
| 44 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).max |
| 45 | + 7 |
| 46 | + >>> max_min_divide_conquer(arr, 0, len(arr) - 1).min |
| 47 | + 1 |
| 48 | + """ |
| 49 | + result = Pair() |
| 50 | + |
| 51 | + # If only one element in the array |
| 52 | + if low == high: |
| 53 | + result.max = arr[low] |
| 54 | + result.min = arr[low] |
| 55 | + return result |
| 56 | + |
| 57 | + # If there are two elements in the array |
| 58 | + if high == low + 1: |
| 59 | + if arr[low] < arr[high]: |
| 60 | + result.min = arr[low] |
| 61 | + result.max = arr[high] |
| 62 | + else: |
| 63 | + result.min = arr[high] |
| 64 | + result.max = arr[low] |
| 65 | + return result |
| 66 | + |
| 67 | + # If there are more than two elements in the array |
| 68 | + mid = (low + high) // 2 |
| 69 | + left = max_min_divide_conquer(arr, low, mid) |
| 70 | + right = max_min_divide_conquer(arr, mid + 1, high) |
| 71 | + |
| 72 | + # Compare and get the maximum of both parts |
| 73 | + result.max = max(left.max, right.max) |
| 74 | + |
| 75 | + # Compare and get the minimum of both parts |
| 76 | + result.min = min(left.min, right.min) |
| 77 | + |
| 78 | + return result |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + from doctest import testmod |
| 83 | + |
| 84 | + testmod() |
0 commit comments