Skip to content

Commit

Permalink
Solution and tests for Largest Sum in an Array, llipio#20
Browse files Browse the repository at this point in the history
  • Loading branch information
zachnagatani authored and msach22 committed May 31, 2017
1 parent 0d81fb6 commit 6cf0067
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
31 changes: 31 additions & 0 deletions solutions/20.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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 => {
// Initialize largestSum to the sum of the first two elements in arr
let largestSum = arr[0] + arr[1];

// Loop through arr, adding i + (i + 1) and compare to largestSum, updating as necessary
for (let i = 1; i < arr.length; i++) {
// Set the current sum of the iteration to the current element i and the next element, i + 1
let currentSum = arr[i] + arr[i + 1];

// If currentSum is larger than largestSum, update accordingly, else leave as is
largestSum = currentSum > largestSum ? currentSum : largestSum;
}

return largestSum;
};

module.exports = {
solution
};
18 changes: 18 additions & 0 deletions test/20.js
Original file line number Diff line number Diff line change
@@ -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);
})
});

0 comments on commit 6cf0067

Please sign in to comment.