diff --git a/solutions/20.js b/solutions/20.js new file mode 100644 index 0000000..c71d416 --- /dev/null +++ b/solutions/20.js @@ -0,0 +1,26 @@ +// Largest Sum in an Array +// Return the largest sum of 2 consecutive numbers given an array +// input: [1, 2, 9, 0, 10] +// output: 11 + +// Zach Nagatani + +/** + * Uses a greedy approach to track the largestSum so far, updating as necessary + * @param {Number[]} arr - an array of numbers + * @returns {Number} largestSum - the largestSum of two consecutive numbers in arr + */ +const solution = arr => { + let largestSum = arr[0] + arr[1]; + + for (let i = 1; i < arr.length; i++) { + let currentSum = arr[i] + arr[i + 1]; + largestSum = currentSum > largestSum ? currentSum : largestSum; + } + + return largestSum; +}; + +module.exports = { + solution +}; \ No newline at end of file diff --git a/test/20.js b/test/20.js new file mode 100644 index 0000000..603c46d --- /dev/null +++ b/test/20.js @@ -0,0 +1,18 @@ +const expect = require('chai').expect; +let solution = require('../solutions/20').solution; +//solution = require('../yourSolution').solution; + +describe('largest sum in array', () => { + it('should return 11 for [1,2,9,0,10]', () => { + const result = solution([1,2,9,0,10]); + expect(result).to.equal(11); + }); + it('should return 46 for [13,14,32,3,17,6]', () => { + const result = solution([13,14,32,3,17]); + expect(result).to.equal(46); + }); + it('should work with negative numbers [-1,-2,-9,-3,-10]', () => { + const result = solution([-1,-2,-9,-3,-10]); + expect(result).to.equal(-3); + }) +});