Max & min in a 2D array

Find extremes across the whole grid, or build lists of max and min — one pair per row, or one pair per column.

Programming Beginner 2D arrays · Comparisons ~8 min
The idea

One pair — or a pair for each line

Seed max and min from the first cell, then compare as you scan. For every row (or column), re-seed and append both results to lists.

TipGreen marks the current max; mint marks the current min.
IdeaSeed then scan
row_max_min.pyPython
row_maxs, row_mins = [], []
for r in range(rows):
    max_val = min_val = grid[r][0]
    for c in range(1, cols):
        if grid[r][c] > max_val: max_val = grid[r][c]
        if grid[r][c] < min_val: min_val = grid[r][c]
    row_maxs.append(max_val)
    row_mins.append(min_val)
Interactive

Run the simulation

Compare each cell against the running max and min. Trays hold finished line results.

Step 0 / 0
demo.pyPython
Matrix + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

2D max & min essentials

Whole grid vs a list of line extremes.

All

One max, one min

Seed from grid[0][0], then scan the rest of the matrix.

Rows

Re-seed each row

Append into row_maxs and row_mins after each row finishes.

Columns

Same idea, swap axes

col_maxs / col_mins store one pair per column.