Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Index of Maximum Element

Find the zero-based position of a list's maximum. Students track both a candidate value and its index and see why equal maxima keep the first position.

BeginnerPhase 4 - Level 1: Basic ArraysExample 7 of 10
index-of-maximum-element.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Find index of max
8max_index = 0
9max_value = arr[0]
10
11for i in range(1, len(arr)):
12 if arr[i] > max_value:
13 max_value = arr[i]
14 max_index = i
15
16print(f"Index of maximum: {max_index}")

Output

Enter array size: 5
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 30
Element 5: 15
Index of maximum: 3

In this one

  • Track a value-index pair
  • Use zero-based positions
  • Retain first tied maxima

How it works

  1. 1

    Initialize max_index zero and max_value from arr[0].

  2. 2

    Scan later indexes for a larger value.

  3. 3

    Update both candidate fields together before printing the index.

Edge cases

What if the maximum repeats?

What if the maximum repeats?

The first occurrence's index is kept.

What if n = 0?

What if n = 0?

arr[0] raises IndexError.

What's going on

The initial maximum and index come from position zero. The loop then scans positions one through the last valid index.

A strictly larger value updates max_value and max_index together. Equal values do not replace them, so ties keep the first maximum's index. The input must be nonempty because arr[0] is read before the scan begins.

What if the maximum repeats? The first occurrence's index is kept.

What if n = 0? arr[0] raises IndexError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Does the output use one-based positions?

Pick an answer to check it.

Question 2

What if the maximum repeats?

Pick an answer to check it.

Questions people ask

What if the maximum repeats?

The first occurrence's index is kept.

What if n = 0?

arr[0] raises IndexError.

Does the output use one-based positions?

No, it reports a zero-based index.