Solution 1 - Contribution Counting
Each arr[i] appears in (i+1)*(n-i) subarrays; half (rounded up) are odd-length.
Each arr[i] appears in (i+1)*(n-i) subarrays; half (rounded up) are odd-length.
""" 1588.1 - Sum of All Odd Length Subarrays - Solution 1 - Contribution """
from typing import List
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
n = len(arr)
total = 0
for i, x in enumerate(arr):
total_subarrays = (i + 1) * (n - i)
odd_subarrays = (total_subarrays + 1) // 2
total += x * odd_subarrays
return total