Chapter 10
HomeFinding the smallest or largest value in a collection is one of the most fundamental algorithmic patterns. Every language has built-in helpers — but it's important to understand the manual loop first.
Start with the first element as your candidate. Then compare every other element against it, updating if you find a better one.
Given N and N integers, print the smallest value.
Sample input: 5 8 3 9 1 6 Expected output: 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
int min_val = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min_val) {
min_val = arr[i];
}
}
cout << min_val << "\n";
return 0;
}
use std::io::{self, Read};
fn main() {
let mut input = String::new();
io::stdin().lock().read_to_string(&mut input).unwrap();
let nums: Vec<i32> = input
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let n = nums[0] as usize;
let arr = &nums[1..=n];
let mut min_val = arr[0];
for &x in &arr[1..] {
if x < min_val { min_val = x; }
}
println!("{}", min_val);
}
In contest code you'll use the built-in helpers — they're faster to write and less error-prone. But knowing the manual loop helps you understand how they work.
int min_val = *min_element(arr.begin(), arr.end()); int max_val = *max_element(arr.begin(), arr.end()); // or both at once: auto [lo, hi] = minmax_element(arr.begin(), arr.end()); cout << *lo << " " << *hi << "\n";
let min_val = arr.iter().min().unwrap();
let max_val = arr.iter().max().unwrap();
// or both at once — iterate once:
let min = arr.iter().min();
let max = arr.iter().max();
println!("{} {}", min.unwrap(), max.unwrap());
When you need both min and max, you can find them in a single pass. Compare pairs of elements to reduce the number of comparisons.
Given N and N integers, print the difference between the largest and smallest.
Sample input: 4 7 2 10 3 Expected output: 8
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
int x; cin >> x;
int lo = x, hi = x;
for (int i = 1; i < n; i++) {
cin >> x;
if (x < lo) lo = x;
if (x > hi) hi = x;
}
cout << hi - lo << "\n";
return 0;
}
use std::io::{self, Read};
fn main() {
let mut input = String::new();
io::stdin().lock().read_to_string(&mut input).unwrap();
let nums: Vec<i32> = input
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let arr = &nums[1..];
let lo = arr.iter().min().unwrap();
let hi = arr.iter().max().unwrap();
println!("{}", hi - lo);
}
arr[0], compare each other element.
min_element / max_element (C++) or .min() / .max() (Rust).