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

1 Answer

0 votes
fun main() {
    // Define the list
    val lst = listOf(1, 3, 7, 9, 2, 8, 5, 4)

    // Create a sublist of the list (from index 1 to 5, exclusive of 5)
    val subset = lst.subList(1, 5) // This gives [3, 7, 9, 2]

    // Find the maximum value in the subset
    val max = subset.maxOrNull() ?: throw IllegalArgumentException("Empty list")

    // Find the minimum value in the subset
    val min = subset.minOrNull() ?: throw IllegalArgumentException("Empty list")

    println("Max: $max")
    println("Min: $min")
}


     
/*
run:
  
Max: 9
Min: 2
 
*/

 



answered Mar 25, 2025 by avibootz
...