카테고리 없음

알고리즘 연습

그란. 2021. 3. 8. 11:17

Q. 리스트항목중 최대값과 최소값의 차이가 가장 큰 항목의 인덱스 구하기

 

A. a에서는 a[2]의 차이가 10으로 가장 크므로 2가 출력되어야함 

val a = listOf(
    listOf(1, 1),
    listOf(6, 3),
    listOf(9, 19)
)



1번 방법 

var maxIndex = 0
var maxDifference = 0

a.forEachIndexed { index, item ->

    val difference = item.max()!! - item.min()!!
    if (difference > maxDifference) {
        maxIndex = index
        maxDifference = difference
    }
}

maxIndex


2번 방법 

a.indexOf(a.maxBy {
    it.max()!! - it.min()!!
})