LeetCode 1588. Sum of All Odd Length Subarrays
考点 | 难度 |
---|---|
Prefix Sum | Easy |
题目
Given an array of positive integers arr
, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr
.
思路
对于每个A[i]
,从A[0]
到A[i]
中有i+1
种选择,从A[i]
到A[n-1]
有n-i
种选择,所以一共有k = (i+1)*(n-i)
中含有A[i]
的subarray,其中k/2
个的长度是奇数。所以A[i]
被数((i + 1) * (n - i) + 1) / 2
次。
答案
public int sumOddLengthSubarrays(int[] A) {
int res = 0, n = A.length;
for (int i = 0; i < n; ++i) {
res += ((i + 1) * (n - i) + 1) / 2 * A[i];
}
return res;
}