0%

Leetcode 1588. Sum of All Odd Length Subarrays

題目

1
2
3
4
5
6
7
8
9
10
11
12
13
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

解法思維

利用slice()取出奇數列再加總

1
2
3
4
// 取頭不取尾
let arr=[1,2,3,4]
arr.slice(0,1) // 1
arr.slice(0,3) // 1,2,3
1
2
3
4
5
6
7
8
9
10
11
const sumOddLengthSubarrays= arr => {
let sum = 0;
for (let i = 1; i <= arr.length; i += 2) {
for (let j = 0; j <= arr.length - i; j++) {
let odd = arr.slice(j, j + i);
console.log(j,odd)
sum += odd.reduce((acc, cv) => acc + cv, 0);
}
}
return sum;
};