From 1c828f2ab15a685d1a41c31ddc3b1a31acec75e1 Mon Sep 17 00:00:00 2001 From: emyarod Date: Tue, 27 Feb 2018 10:16:52 -0500 Subject: [PATCH 1/2] Add O(n) maximum subarray test --- test/searching/maximum-subarray.spec.js | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 test/searching/maximum-subarray.spec.js diff --git a/test/searching/maximum-subarray.spec.js b/test/searching/maximum-subarray.spec.js new file mode 100644 index 00000000..66daa8c7 --- /dev/null +++ b/test/searching/maximum-subarray.spec.js @@ -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); + }); +}); From 1fe106d531b442d06777faee9c2cd98d7b6e3247 Mon Sep 17 00:00:00 2001 From: emyarod Date: Tue, 27 Feb 2018 10:17:06 -0500 Subject: [PATCH 2/2] Fix O(n) maximum subarray solution --- src/searching/maximum-subarray.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/searching/maximum-subarray.js b/src/searching/maximum-subarray.js index 4628369e..85ae9d11 100644 --- a/src/searching/maximum-subarray.js +++ b/src/searching/maximum-subarray.js @@ -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;