liveBook · Manning

Maximum

As explained in Grokking Data Structures

A maximum value is the greatest element in a collection under the relevant ordering.

A maximum is the greatest value in a collection according to its ordering. In an array, find it by scanning each element and updating the stored value when a larger one appears. section 2.16

Two practical ways to locate a maximum are:

  • In an array, initialize the candidate from the first element, compare later elements against it, and retain the value and index. section 2.16
  • In a binary search tree, start at the root and follow right-child links until reaching a node with no right child. section 11.9
  • For a tree node, apply the same rightward traversal to find the maximum of its subtree and return the node with its parent. section 11.9

Die-roll counters

After recording die rolls in six counters, scan the counters to find the most frequent face. Return both the counter's value and its index; adjust the index by one to name the die face. section 2.16

Replacing a deleted tree node

When deleting a BST node with two children, replace its value with the maximum of its left subtree. That predecessor can then be removed through a simpler deletion case. section 11.11

def max_in_array(array):
    if len(array) == 0:
        raise Exception('Max of an empty array')
    max_index = 0
    for index in range(1, len(array)):
        if array[index] > array[max_index]:
            max_index = index
    return max_index, array[max_index]

The implementation scans an array, rejects an empty input, tracks the maximum index, and returns both the index and value. section 2.16

How Grokking Data Structures covers it

How deep it goes
Explains array scanning, BST traversal, subtree results, deletion use, and O(h) operation cost.
Examples
Demonstrates maximum through die-roll counters and replacing a deleted BST node with its left-subtree predecessor.
What it assumes
Assumes basic arrays or BST ordering and develops the maximum search from traversal behavior.
What you can do after
Apply it via array scans or rightward BST traversal, returning the maximum value and, when needed, its location.
How it connects
Connects maximum with array traversal, binary search trees, subtrees, minimum, predecessor, and deletion.

Also explained in

Compare how 4 books explain maximum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.