Skip to content

Commit f711bee

Browse files
authored
Add Maximum Subarray in Javascript (#5098)
1 parent 1945ccb commit f711bee

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function printUsage() {
2+
console.log(
3+
'Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"',
4+
);
5+
}
6+
7+
function maxSubarraySum(arr) {
8+
let maxSoFar = -Infinity;
9+
let maxEndingHere = 0;
10+
11+
for (let num of arr) {
12+
maxEndingHere += num;
13+
14+
if (maxSoFar < maxEndingHere) {
15+
maxSoFar = maxEndingHere;
16+
}
17+
18+
if (maxEndingHere < 0) {
19+
maxEndingHere = 0;
20+
}
21+
}
22+
23+
return maxSoFar;
24+
}
25+
26+
function main() {
27+
const args = process.argv.slice(2);
28+
29+
if (args.length < 1 || args[0] === "") {
30+
printUsage();
31+
process.exit(1);
32+
}
33+
const input = args[0];
34+
const arr = input.split(",").map((token) => parseInt(token.trim(), 10));
35+
36+
if (arr.length === 1) {
37+
console.log(arr[0]);
38+
return;
39+
} else if (arr.length === 0) {
40+
printUsage();
41+
process.exit(1);
42+
}
43+
const result = maxSubarraySum(arr);
44+
45+
console.log(result);
46+
}
47+
48+
main();

0 commit comments

Comments
 (0)