티스토리 뷰
주어진 배열을 홀수로 잘랐을때, 나올 수 있는 모든 배열의 합을 구하는 문제입니다.
1) filter로 배열의 길이가 홀수인지 확인
2) 현재 index + oddLength가 전체 배열의 길이보다 작은지 확인
이 두가지 조건을 통과했다면 합을 구할 수 있으므로 배열을 range로 copy하고, copy한 배열의 모든 정수를 더해주면 됩니다.
class Solution {
fun sumOddLengthSubarrays(arr: IntArray): Int {
var answer : Int = 0
for(i in 0..arr.size-1) {
(1..arr.size)
.filter(this::isOdd)
.filter{ isLessLimited(i+it, arr.size)}
.forEach { answer += sumOfArray(arr.copyOfRange(i, i+it)) }
}
return answer
}
fun sumOfArray(arr: IntArray): Int = arr.reduce { acc, num -> acc + num }
fun isOdd(num: Int) : Boolean = (num % 2 == 1)
fun isLessLimited(index : Int, limited : Int) : Boolean = index <= limited
}
'PS > LeetCode' 카테고리의 다른 글
[Kotlin] LeetCode 2079 : Watering Plants (0) | 2022.12.03 |
---|---|
[Kotlin] LeetCode 2130 : maximum-twin-sum-of-a-linked-list (0) | 2022.11.30 |
[Kotlin] LeetCode 1302 : Deepest Leaves Sum (0) | 2022.11.28 |
[Kotlin] LeetCode 1512 : Number of Good Pairs (0) | 2022.11.27 |
[Kotlin] LeetCode 009 : Palindrome Number (2) | 2022.11.27 |