Smallest Range I

Here’s another short answer for an easy LC problem.

class Solution {
    fun smallestRangeI(A: IntArray, K: Int): Int {
        return A.sorted().let {
            val min = it.first()
            val max = it.last()
            
            if(min + K > max - K) 0 else (max - K) - (min + K)
        }
    }
}

We’ll sort the array and get the first and the last element which will represent the min and max values respectively. We will use them to compute the final output.

Not the fastest but the code is elegant so this’ll do for now.

Runtime: 256 ms, faster than 8.33% of Kotlin online submissions for Smallest Range I.
Memory Usage: 38.7 MB, less than 100.00% of Kotlin online submissions for Smallest Range I.
comments powered by Disqus