2025-08-09 13:17:16 +0000 UTC
Sum of All Odd Length Subarrays
Categories:
Links
Code
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
length = len(arr)
answer = 0
for i, num in enumerate(arr):
left, right = i, length - i - 1
odd_left, odd_right = (left // 2) + 1, (right // 2) + 1
even_left, even_right = (left + 1) // 2, (right + 1) // 2
sub_count = (odd_left * odd_right) + (even_left * even_right)
answer += num * sub_count
return answer