Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1fe106d

Browse files
committed
Fix O(n) maximum subarray solution
1 parent 1c828f2 commit 1fe106d

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

src/searching/maximum-subarray.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@
2020
* @return {Number} Maximum sum of the elements of a subarray.
2121
*/
2222
function maxSubarray(array) {
23-
var currentMax = 0;
24-
var max = 0;
25-
26-
for (var i = 0; i < array.length; i += 1) {
27-
currentMax = Math.max(0, currentMax + array[i]);
23+
var currentMax = array[0];
24+
var max = array[0];
25+
for (var i = 1; i < array.length; i += 1) {
26+
currentMax = Math.max(array[i], currentMax + array[i]);
2827
max = Math.max(max, currentMax);
2928
}
3029
return max;

0 commit comments

Comments
 (0)