Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions 1588.sum-of-all-odd-length-subarrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* URL of this problem
* https://leetcode.com/problems/sum-of-all-odd-length-subarrays/description/
*
* @param {number[]} arr
* @return {number}
*/

var sumOddLengthSubarrays = function(arr) {
let SubarraySum = 0;

for (let i = 1; i <= arr.length; i += 2) {
for (let j = 0; i + j <= arr.length; j++) {
const Subarray = arr.slice(j, i + j);
const Sum = Subarray.reduce((sum, curr) => sum + curr);

SubarraySum += Sum;
}
}

return SubarraySum;
}

module.exports = sumOddLengthSubarrays;
17 changes: 17 additions & 0 deletions sumOddLengthSubarrays.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const sumOddLengthSubarrays = require("./1588.sum-of-all-odd-length-subarrays");

test("Return the sum of all the odd-length subarrays in the input arr", () => {
expect(sumOddLengthSubarrays([1,4,2,5,3])).toBe(58);
});

test("Return 0 if the input arr is empty", () => {
expect(sumOddLengthSubarrays([])).toBe(0);
});

test("Return Infinity if the input arr includes Infinity", () => {
expect(sumOddLengthSubarrays([1,4,2,5,3,Infinity])).toBe(Infinity);
});

test("Return -Infinity if the input arr includes -Infinity", () => {
expect(sumOddLengthSubarrays([1,4,2,5,3,-Infinity])).toBe(-Infinity);
});