Go Program to Find Largest Element in Slice
max := slice[0]; for _, v := range slice { if v > max { max = v } }.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { nums := []int{3, 5, 1, 9, 2} max := nums[0] for _, v := range nums { if v > max { max = v } } fmt.Println(max) }
Dry Run
Let's trace the slice [3, 5, 1, 9, 2] through the code
Initialize max
max = 3 (first element)
Compare 3 with max
3 is not greater than 3, max stays 3
Compare 5 with max
5 is greater than 3, max updated to 5
Compare 1 with max
1 is not greater than 5, max stays 5
Compare 9 with max
9 is greater than 5, max updated to 9
Compare 2 with max
2 is not greater than 9, max stays 9
Return max
max = 9
| Iteration | Current Value | Max Value |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 5 | 5 |
| 3 | 1 | 5 |
| 4 | 9 | 9 |
| 5 | 2 | 9 |
Why This Works
Step 1: Start with first element
We assume the first number is the largest to have a starting point for comparison.
Step 2: Compare each element
Each number is checked against the current largest number using if v > max.
Step 3: Update largest number
If a bigger number is found, we update max to that number to keep track of the largest.
Alternative Approaches
package main import ( "fmt" "sort" ) func main() { nums := []int{3, 5, 1, 9, 2} sort.Ints(nums) fmt.Println(nums[len(nums)-1]) }
package main import "fmt" func maxInSlice(nums []int) int { max := nums[0] for _, v := range nums { if v > max { max = v } } return max } func main() { fmt.Println(maxInSlice([]int{3, 5, 1, 9, 2})) }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so the time grows linearly with the slice size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The single pass loop is fastest because it only scans once. Sorting is slower (O(n log n)) but simpler to write.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single pass loop | O(n) | O(1) | Fastest for large slices |
| Sorting slice | O(n log n) | O(1) | Simple code, small slices |
| Function wrapper | O(n) | O(1) | Reusable and clean code |