티스토리 뷰

 

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
    
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함