MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / maxSubArray

Function maxSubArray

arrays/max-subarray.js:4–16  ·  view source on GitHub ↗
(nums)

Source from the content-addressed store, hash-verified

2// O(1) space
3// difficulty MEDIUM
4var maxSubArray = function (nums) {
5 let maxSub = nums[0];
6 let currentSum = 0;
7
8 for (const num of nums) {
9 if (currentSum < 0) {
10 currentSum = 0;
11 }
12 currentSum += num;
13 maxSub = Math.max(maxSub, currentSum);
14 }
15 return maxSub;
16};
17
18const nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
19console.log(maxSubArray(nums));

Callers 1

max-subarray.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected