Sum of All Odd Length Subarrays

easy array math prefix sum

Problem

Given a positive integer array arr, return the sum of all possible odd-length subarrays.

Inputarr = [1,4,2,5,3]
Output58
All odd-length contiguous subarrays summed.

def sum_odd_length_subarrays(arr):
    n = len(arr); total = 0
    for i, v in enumerate(arr):
        left, right = i + 1, n - i
        full = left * right
        odd = (full + 1) // 2
        total += v * odd
    return total
function sumOddLengthSubarrays(arr) {
  const n = arr.length; let total = 0;
  for (let i = 0; i < n; i++) {
    const left = i + 1, right = n - i;
    const full = left * right, odd = (full + 1) >> 1;
    total += arr[i] * odd;
  }
  return total;
}
class Solution {
    public int sumOddLengthSubarrays(int[] arr) {
        int n = arr.length, total = 0;
        for (int i = 0; i < n; i++) {
            int left = i + 1, right = n - i;
            int full = left * right, odd = (full + 1) / 2;
            total += arr[i] * odd;
        }
        return total;
    }
}
int sumOddLengthSubarrays(vector& arr) {
    int n = arr.size(), total = 0;
    for (int i = 0; i < n; i++) {
        int left = i + 1, right = n - i;
        int full = left * right, odd = (full + 1) / 2;
        total += arr[i] * odd;
    }
    return total;
}
Time: O(n) Space: O(1)