forked from llipio/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solution and tests for Largest Sum in an Array, llipio#20
- Loading branch information
1 parent
0d81fb6
commit 6cf0067
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}) | ||
}); |