Lesson 16 of 50 beginner

Finding Min, Max, and Searching

Learn to find the smallest, largest, and search for values — three skills every CP contestant needs!

Open interactive version (quiz + challenge)

Real-world analogy

Imagine you are at a candy store with a row of price tags. To find the cheapest candy (min), you look at every price tag and remember the lowest one you have seen so far. To find the most expensive (max), you remember the highest. To search for a candy that costs exactly $5, you check each tag until you find it. That is exactly how min, max, and search work on arrays!

What is it?

Finding min, max, and searching are fundamental array operations. Min/max find the extreme values by scanning through all elements and tracking the best seen so far. Linear search checks each element until a match is found.

Real-world relevance

Your phone's weather app finds the week's highest and lowest temperatures using min/max. When you search for a contact by name, your phone does a search through a list. When a game shows 'High Score,' it found the maximum of all stored scores. These operations are everywhere!

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[n];
    
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    // Find maximum and its position
    int maxVal = arr[0], maxIdx = 0;
    for (int i = 1; i < n; i++) {
        if (arr[i] > maxVal) {
            maxVal = arr[i];
            maxIdx = i;
        }
    }
    cout << "Max: " << maxVal << " at index " << maxIdx << endl;
    
    // Find minimum
    int minVal = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] < minVal) {
            minVal = arr[i];
        }
    }
    cout << "Min: " << minVal << endl;
    
    // Search for a value
    int target;
    cin >> target;
    int foundIdx = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            foundIdx = i;
            break;  // Found it, stop searching!
        }
    }
    
    if (foundIdx != -1) {
        cout << target << " found at index " << foundIdx << endl;
    } else {
        cout << target << " not found!" << endl;
    }
    
    return 0;
}
// Input:  5
//         3 7 1 9 4
//         7
// Output: Max: 9 at index 3
//         Min: 1
//         7 found at index 1

Line-by-line walkthrough

  1. 1. We read the array using our standard input pattern.
  2. 2. For maximum: we assume arr[0] is the max, then check every other element starting from index 1.
  3. 3. If arr[i] > maxVal, we update both maxVal and maxIdx to remember the new champion.
  4. 4. Finding minimum is the same but we check arr[i] < minVal instead.
  5. 5. For search: we set foundIdx = -1 (meaning 'not found yet').
  6. 6. We loop and check each element. When we find the target, we save the index and break.
  7. 7. After the loop, if foundIdx is still -1, the target was not in the array.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[n];
    
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    int maxVal = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] > maxVal) {
            maxVal = arr[i];
        }
    }
    cout << "Max: " << maxVal << endl;
    
    return 0;
}
// Input: 4
//        -5 -3 -8 -1
// Expected: Max: -1
// Actual Output: Max: 0
Need a hint?
Look at the initial value of maxVal. What if all the numbers in the array are negative?
Show answer
The bug is initializing maxVal to 0! If all elements are negative, none of them are greater than 0, so maxVal stays at 0 — but 0 is not even in the array! The fix is to initialize maxVal = arr[0] (the first actual element) and start the loop from i = 1. This way, the max is always a real element from the array.

Explain like I'm 5

Imagine your mom asks you to find the tallest person in your class. You stand next to the first kid and say 'you are the tallest so far.' Then you go to the next kid — if they are taller, they become the new tallest. You keep going until you have checked everyone. The last person standing as 'tallest' really is the tallest! That is how finding the maximum works.

Fun fact

There is a mathematical proof that you need at least n-1 comparisons to find the minimum (or maximum) of n elements. Nobody can do it with fewer comparisons! But here is a cool trick: you can find BOTH the min AND max together using only about 1.5n comparisons instead of 2n by comparing pairs of elements first.

Hands-on challenge

Read an array of n integers. Find and print: (1) the maximum value, (2) the minimum value, (3) the difference between max and min (called the range), (4) how many times the maximum value appears in the array. Bonus: find the second largest distinct value!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero