PS/LeetCode
[Kotlin] LeetCode 1588 : Sum of All Odd Length Subarrays
뱃싸공
2022. 11. 27. 18:02
Sum of All Odd Length Subarrays - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주어진 배열을 홀수로 잘랐을때, 나올 수 있는 모든 배열의 합을 구하는 문제입니다.
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
}