#1588
Easy Algorithms Sum of all odd length subarrays
Array Math Prefix Sum
83.9% acceptance
Feb 25, 2026
3880
328
Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn sum_odd_length_subarrays(arr: Vec<i32>) -> i32 {
let n = arr.len();
let mut sum = 0;
for i in 0..n {
let mut len = 1;
while i + len <= n {
sum += arr[i..i + len].iter().sum::<i32>();
len += 2;
}
}
sum
}
}