diff --git a/1588.sum-of-all-odd-length-subarrays.js b/1588.sum-of-all-odd-length-subarrays.js new file mode 100644 index 00000000..dbc31840 --- /dev/null +++ b/1588.sum-of-all-odd-length-subarrays.js @@ -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; \ No newline at end of file diff --git a/sumOddLengthSubarrays.test.js b/sumOddLengthSubarrays.test.js new file mode 100644 index 00000000..8417b69a --- /dev/null +++ b/sumOddLengthSubarrays.test.js @@ -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); +}); \ No newline at end of file