1
/*
2
Suppose N is the length of given array.
3
Number of subarrays including element arr[i] is
4
i * (N-i) + (N-i) because there are N-i subarrays with arr[i] as first element
5
and i * (N-i) subarrays with arr[i] as a not-first element. arr[i] appears in
6
(N-i) subarrays for each preceding element and therefore we have i*(N-i).
7

8
Suppose i * (N-i) + (N-i) is `total`. Ceil(total / 2) is the number of odd-length subarrays and Floor(total / 2) is the number of even-length subarrays.
9
When total is odd, there is one more odd-length subarray because of a single-element subarray.
10

11
For each number, we multiply its value with the total number of subarrays it appears and
12
add it to a sum.
13
*/
14
var sumOddLengthSubarrays = function (arr) {
15
let sum = 0,
16
N = arr.length;
17
for (let i = 0; i < arr.length; i++) {
18
let total = i * (N - i) + (N - i);
19
sum += Math.ceil(total / 2) * arr[i];
20
}
21
return sum;
22
// T.C: O(N)
23
// S.C: O(1)
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0