diff --git a/src/_Problems_/max-array-sum/index.js b/src/_Problems_/max-array-sum/index.js new file mode 100644 index 00000000..e9732db4 --- /dev/null +++ b/src/_Problems_/max-array-sum/index.js @@ -0,0 +1,45 @@ +function maxArraySum(array, n) { + if (array.length == 0) { + return "null as the length of array is nil."; + } + else if (array.length < n) { + var str = "null as the length of subarray is less than " + n + "."; + return str; + } + else if (array.length == n) { + var sum = array.reduce(function (a, b) { + return a + b; + }, 0); + return sum; + } + else if (array.length > n) { + var i, j, max; + for (i = 0; i < 1; i++) { + var temp = []; + for (j = i; j < i + n; j++) { + temp.push(array[j]); + } + var sum = temp.reduce(function (a, b) { + return a + b; + }, 0); + max = sum; + } + for (i = 1; i <= array.length - n; i++) { + var temp = []; + for (j = i; j < i + n; j++) { + temp.push(array[j]); + } + var sum = temp.reduce(function (a, b) { + return a + b; + }, 0); + if (sum > max) { + max = sum; + } + } + return max; + } +} + +module.exports = { + maxArraySum, +}; \ No newline at end of file diff --git a/src/_Problems_/max-array-sum/max-array-sum.test.js b/src/_Problems_/max-array-sum/max-array-sum.test.js new file mode 100644 index 00000000..c55667c2 --- /dev/null +++ b/src/_Problems_/max-array-sum/max-array-sum.test.js @@ -0,0 +1,15 @@ +const { maxArraySum } = require('.'); + +describe('Max Array Sum', () => { + it('Should return 10', () => { + expect(maxArraySum([1, 5, 2, 3, 4], 3)).toEqual(10); + }); + + it('Should return 1', () => { + expect(maxArraySum([1, 2, 4], 4)).toEqual("null as the length of subarray is less than 4."); + }); + + it('Should return 120', () => { + expect(maxArraySum([], 2)).toEqual("null as the length of array is nil."); + }); +});