1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// @Title: 所有奇数长度子数组的和 (Sum of All Odd Length Subarrays)
// @Author: 15816537946@163.com
// @Date: 2021-08-29 19:52:46
// @Runtime: 0 ms
// @Memory: 2.2 MB

func sumOddLengthSubarrays(arr []int) int {
	res, lens := 0, len(arr)
	for i := 1; i < lens; i++ {
		arr[i] += arr[i-1]
	}

	for i := 1; i <= lens; i += 2 {
		a, b := 0, i
		res += arr[b-1]
		for b < lens {
			res += arr[b] - arr[a]
			a++
			b++
		}
	}

	return res

}