Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 4 additions & 5 deletions src/searching/maximum-subarray.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@
* @return {Number} Maximum sum of the elements of a subarray.
*/
function maxSubarray(array) {
var currentMax = 0;
var max = 0;

for (var i = 0; i < array.length; i += 1) {
currentMax = Math.max(0, currentMax + array[i]);
var currentMax = array[0];
var max = array[0];
for (var i = 1; i < array.length; i += 1) {
currentMax = Math.max(array[i], currentMax + array[i]);
max = Math.max(max, currentMax);
}
return max;
Expand Down
29 changes: 29 additions & 0 deletions test/searching/maximum-subarray.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var maxSubArray = require('../../src/searching/maximum-subarray').maxSubarray;

describe('Maximum subarray', function() {
'use strict';

it('should work with empty arrays', function() {
expect(maxSubArray([])).toBeUndefined();
});

it('should return the only element when an array with single element is passed', function() {
expect(maxSubArray([42])).toBe(42);
});

it('should return the only negative element when an array with single element is passed', function() {
expect(maxSubArray([-42])).toBe(-42);
});

it('should return the zero when an array with single element, which is zero is passed', function() {
expect(maxSubArray([0])).toBe(0);
});

it('should return the max sum of a subarray', function() {
expect(maxSubArray([1, -1, 2, 3, -1])).toBe(5);
});

it('should return the max negative number when array with negative numbers is provided', function() {
expect(maxSubArray([-10, -1, -2, -3, -1])).toBe(-1);
});
});