1588 | Sum of All Odd Length Subarrays
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/



작성 코드
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
answer = 0
for i in range(1, len(arr) + 1, 2):
for start in range(len(arr) - i + 1):
answer += sum(arr[start : start+i])
return answer
접근 방법
- 슬라이싱할 간격을 i 로 지정, 시작 값을 start 로 지정
이상 코드
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
answer = 0
len_arr = len(arr)
for idx, num in enumerate(arr):
answer += num * (((len_arr - idx) * (idx + 1) + 1) // 2)
return answer

반응형
'Algorithm > LeetCode' 카테고리의 다른 글
| [LeetCode] 896 | Monotonic Array (0) | 2023.03.29 |
|---|---|
| [LeetCode] 217 | Contains Duplicate (0) | 2023.03.09 |
| [LeetCode] 226 | Invert Binary Tree (0) | 2022.05.30 |
| [LeetCode] 191 | Number of 1 Bits (0) | 2022.05.24 |
| [LeetCode] 1523 | Count Odd Numbers in an Interval Range (0) | 2022.05.19 |
댓글