How to find the max and min of a subset of a list in Swift

1 Answer

0 votes
import Foundation

let arr = [1, 3, 7, 9, 2, 8, 5, 4]

// Create a slice of the array (from index 1 to 5, exclusive of 5)
let subset = arr[1..<5] // This gives [3, 7, 9, 2]

// Find the maximum value in the subset
if let max = subset.max() {
    print("Max: \(max)")
} else {
    print("Array is empty, no maximum value.")
}

// Find the minimum value in the subset
if let min = subset.min() {
    print("Min: \(min)")
} else {
    print("Array is empty, no minimum value.")
}

 
 
/*
run:

Max: 9
Min: 2
 
*/

 



answered Mar 25, 2025 by avibootz
...