From 5716752db2a01ee3dafcff61253d896b52141c0f Mon Sep 17 00:00:00 2001 From: Anton Yefremov Date: Tue, 2 May 2017 12:23:04 +0300 Subject: [PATCH] Add maximum subarray function --- README.md | 3 ++- lib/iterative/maxsubarray.js | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 lib/iterative/maxsubarray.js diff --git a/README.md b/README.md index b2c2534..90f918b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ This is a collection of different algorithms, written in JavaScript. The purpose of this package is to define basic algorithms in a concise, - but readable form. However, no (pre)mature optimizations should be expected + but readable form. However, no (pre)mature optimizations should be expected here and code should never be used in production. ## Contents @@ -10,6 +10,7 @@ ### Iterative - [x] coprime + - [x] maxsubarray - [x] prime ### Recursive diff --git a/lib/iterative/maxsubarray.js b/lib/iterative/maxsubarray.js new file mode 100644 index 0000000..1218510 --- /dev/null +++ b/lib/iterative/maxsubarray.js @@ -0,0 +1,18 @@ + +/** + * Expose `maxsubarray`. + */ + +module.exports = maxsubarray; + +function maxsubarray(array) { + var maximum = 0; + var current = 0; + + for (var i = 0; i < array.length; i++) { + current = Math.max(0, current + array[i]); + maximum = Math.max(maximum, current); + } + + return maximum; +}