Kotlin Program to Find Largest Number in a List
You can find the largest number in a list in Kotlin using
list.maxOrNull(), for example: val largest = list.maxOrNull().Examples
Input[3, 5, 1, 9, 2]
Output9
Input[10, 10, 10]
Output10
Input[]
Outputnull
How to Think About It
To find the largest number in a list, look at each number one by one and remember the biggest number you have seen so far. At the end, the number you remembered is the largest.
Algorithm
1
Get the list of numbers.2
Start with the first number as the largest.3
Compare each number in the list with the current largest number.4
If a number is bigger, update the largest number.5
After checking all numbers, return the largest number.Code
kotlin
fun main() {
val numbers = listOf(3, 5, 1, 9, 2)
val largest = numbers.maxOrNull()
println(largest)
}Output
9
Dry Run
Let's trace the list [3, 5, 1, 9, 2] through the code.
1
Initialize list
numbers = [3, 5, 1, 9, 2]
2
Find max
largest = numbers.maxOrNull() -> 9
3
Print result
Print 9
| Iteration | Current Number | Current Largest |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 5 | 5 |
| 3 | 1 | 5 |
| 4 | 9 | 9 |
| 5 | 2 | 9 |
Why This Works
Step 1: Use maxOrNull() function
The maxOrNull() function checks all elements and returns the largest one or null if the list is empty.
Step 2: Handle empty list
If the list is empty, maxOrNull() returns null, so the program won't crash.
Step 3: Print the largest number
The program prints the largest number found in the list.
Alternative Approaches
Manual loop to find largest
kotlin
fun main() {
val numbers = listOf(3, 5, 1, 9, 2)
var largest = numbers[0]
for (num in numbers) {
if (num > largest) {
largest = num
}
}
println(largest)
}This method uses a loop to find the largest number manually, which is more verbose but shows the logic clearly.
Using reduce function
kotlin
fun main() {
val numbers = listOf(3, 5, 1, 9, 2)
val largest = numbers.reduce { max, current -> if (current > max) current else max }
println(largest)
}This uses <code>reduce</code> to compare elements pairwise, which is concise but requires the list to be non-empty.
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so it takes time proportional to the number of elements, which is O(n).
Space Complexity
It uses only a few variables regardless of list size, so space is O(1).
Which Approach is Fastest?
Using maxOrNull() is efficient and concise; manual loops and reduce have similar performance but more code.
| Approach | Time | Space | Best For |
|---|---|---|---|
| maxOrNull() | O(n) | O(1) | Simple and safe for any list |
| Manual loop | O(n) | O(1) | Learning and understanding logic |
| reduce() | O(n) | O(1) | Concise code but non-empty lists only |
Use
maxOrNull() for a simple and safe way to find the largest number in a list.Trying to use
max() on an empty list causes an error; prefer maxOrNull() to avoid this.