Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution and tests for Largest Sum in an Array, #20 #49

Merged
merged 2 commits into from
May 12, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zachnagatani code looks great, but please remove the comments inside of the solution such as commenting before a variable declaration or loop, etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@msach22 Thanks! They've been removed and pushed


// 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);
})
});