find max recursion Algorithm

The find max recursion algorithm is a technique used in computer programming to search for the maximum value within an array or list of elements using the concept of recursion. Recursion is a problem-solving approach where a function calls itself as a subroutine to solve smaller instances of the same problem. In the case of the find max recursion algorithm, the problem to be solved is to find the maximum value within a given list or array of elements. The algorithm works by recursively dividing the list into smaller sublists and comparing the maximum value of each sublist until the overall maximum value is found. The find max recursion algorithm begins by checking the base case, which is when the input list has only one element. In this case, the maximum value is simply the single element present in the list. If the base case is not met, the algorithm proceeds by dividing the list into two halves and calling itself recursively on each half. This process continues until the base case is reached for each sublist, and the maximum values from each sublist are returned. The algorithm then compares the returned maximum values from the two sublists and returns the larger value as the overall maximum. This backtracking and comparison process continues until the final maximum value is obtained from the entire input list.
# Divide and Conquer algorithm
def find_max(nums, left, right):
    """
    find max value in list
    :param nums: contains elements
    :param left: index of first element
    :param right: index of last element
    :return: max in nums

    >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
    >>> find_max(nums, 0, len(nums) - 1) == max(nums)
    True
    """
    if left == right:
        return nums[left]
    mid = (left + right) >> 1  # the middle
    left_max = find_max(nums, left, mid)  # find max in range[left, mid]
    right_max = find_max(nums, mid + 1, right)  # find max in range[mid + 1, right]

    return left_max if left_max >= right_max else right_max


if __name__ == "__main__":
    nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
    assert find_max(nums, 0, len(nums) - 1) == 10

LANGUAGE:

DARK MODE: