티스토리 뷰
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
}
'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 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 공지
- Operating System
- cs
- ARP
- effective
- paging
- GORM
- OS
- fiber
- algorithm
- Effective Java
- Database
- mmu
- java
- soft delete
- network
- go
- spring
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
글 보관함