-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumArray.js
More file actions
27 lines (23 loc) · 712 Bytes
/
sumArray.js
File metadata and controls
27 lines (23 loc) · 712 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Given an array of numbers, calculate the greatest contiguous sum of numbers in it.
// A single array item will count as a contiguous sum.
function sumArray (array) {
var greatest = -Infinity;
for (var index = 0; index < array.length; index++) {
var sum = array[index];
// Need to check if single number is greatest contiguous sum
if (sum > greatest) {
greatest = sum;
}
for (var next = index + 1; next < array.length; next++) {
if (sum + array[next] <= 0) {
break;
}
sum += array[next];
// Check if current sum is greatest contiguous sum
if (sum > greatest) {
greatest = sum;
}
}
}
return greatest;
}