[Kotlin] Korean Coding Test - Programmers - Maximum and minimum values

Kotlin

Language :

Question

Link

The string s contains numbers separated by spaces. Find the minimum and maximum values of the numbers appearing in str and complete the function, solution, which returns a string in the form of "(minimum) (maximum)".

For example, if s is "1 2, 3 4", return "14", and if s is "-1 -2 -3 -4", return "-4 -1".

Restrictions

s has more than one integer separated by a space.

Input/Output example

Input/Output example #1

  • Input: "1 2 3 4"
  • Output: "1 4"

Input/Output example #2

  • Input: "-1 -2 -3 -4"
  • Output: "-4 -1"

Input/Output example #3

  • Input: "-1 -1"
  • Output: "-1 -1"

Code 1

kotlin

class Solution {
    fun solution(s: String): String {
        var min = Int.MAX_VALUE
        var max = Int.MAX_VALUE * -1
        s.split(" ").forEach {
            min = minOf(it.toInt(), min)
            max = maxOf(it.toInt(), max)
        }
        return "$min $max"
    }
}

text

TEST 1 〉	Pass (20.70ms, 63.3MB)
TEST 2 〉	Pass (26.41ms, 61.3MB)
TEST 3 〉	Pass (19.38ms, 62.5MB)
TEST 4 〉	Pass (17.34ms, 61.3MB)
TEST 5 〉	Pass (21.57ms, 61.2MB)
TEST 6 〉	Pass (17.03ms, 61.6MB)
TEST 7 〉	Pass (17.00ms, 63.2MB)
TEST 8 〉	Pass (16.63ms, 60.9MB)
TEST 9 〉	Pass (18.67ms, 62.5MB)
TEST 10 〉	Pass (19.15ms, 61.4MB)
TEST 11 〉	Pass (23.98ms, 61MB)
TEST 12 〉	Pass (17.52ms, 61MB)

Code 2

kotlin

class Solution {
    fun solution(s: String): String {
        return s.split(" ").map { it.toInt() }.sorted().let { "${it.first()} ${it.last()}" }
    }
}
  • Programmes compilation version issue or min(), max() not available and first(), last() after sorting

text

TEST 1 〉	Pass (45.34ms, 64.9MB)
TEST 2 〉	Pass (40.45ms, 65.4MB)
TEST 3 〉	Pass (38.93ms, 65.4MB)
TEST 4 〉	Pass (45.06ms, 65.1MB)
TEST 5 〉	Pass (32.97ms, 64.4MB)
TEST 6 〉	Pass (32.40ms, 64.4MB)
TEST 7 〉	Pass (33.80ms, 64.4MB)
TEST 8 〉	Pass (34.29ms, 64.6MB)
TEST 9 〉	Pass (46.71ms, 64.4MB)
TEST 10 〉	Pass (35.72ms, 64.6MB)
TEST 11 〉	Pass (32.11ms, 64.7MB)
TEST 12 〉	Pass (33.46ms, 64.5MB)

Code 3

kotlin

class Solution {
    fun solution(s: String): String {
        return s.split(" ").sortedBy { it.toInt() }.let { "${it.first()} ${it.last()}" }
    }
}

text

TEST 1 〉	Pass (59.22ms, 63.9MB)
TEST 2 〉	Pass (38.02ms, 66.2MB)
TEST 3 〉	Pass (56.48ms, 64.5MB)
TEST 4 〉	Pass (46.43ms, 64.8MB)
TEST 5 〉	Pass (40.38ms, 65.7MB)
TEST 6 〉	Pass (38.56ms, 64.6MB)
TEST 7 〉	Pass (38.30ms, 64.9MB)
TEST 8 〉	Pass (40.50ms, 65.1MB)
TEST 9 〉	Pass (53.86ms, 64.7MB)
TEST 10 〉	Pass (55.25ms, 65.2MB)
TEST 11 〉	Pass (42.85ms, 65.3MB)
TEST 12 〉	Pass (43.26ms, 64.9MB)

민갤

Back-End Developer

백엔드 개발자입니다.