Skip to content

Commit e693a0d

Browse files
authored
Add Maximum Subarray in TypeScript (#5090)
Add maximum subarray sum implementation in TypeScript
1 parent 1374a68 commit e693a0d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
function printUsage(): void {
2+
console.log('Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"');
3+
}
4+
5+
function maxSubarraySum(arr: number[]): number {
6+
let maxSoFar = Number.MIN_SAFE_INTEGER;
7+
let maxEndingHere = 0;
8+
9+
for (let i = 0; i < arr.length; i++) {
10+
maxEndingHere += arr[i];
11+
12+
if (maxSoFar < maxEndingHere) {
13+
maxSoFar = maxEndingHere;
14+
}
15+
16+
if (maxEndingHere < 0) {
17+
maxEndingHere = 0;
18+
}
19+
}
20+
21+
return maxSoFar;
22+
}
23+
24+
function main(): void {
25+
const args = process.argv.slice(2);
26+
27+
if (args.length < 1) {
28+
printUsage();
29+
process.exit(1);
30+
}
31+
32+
// Check if input is empty
33+
if (args[0].length === 0) {
34+
printUsage();
35+
process.exit(1);
36+
}
37+
38+
// Parse input string
39+
const arr = args[0].split(',').map(s => parseInt(s.trim()));
40+
41+
// If less than two integers were provided
42+
if (arr.length === 1) {
43+
console.log(arr[0]);
44+
return;
45+
} else if (arr.length < 1) {
46+
printUsage();
47+
process.exit(1);
48+
}
49+
50+
// Calculate maximum subarray sum
51+
const result = maxSubarraySum(arr);
52+
53+
console.log(result);
54+
}
55+
56+
main();

0 commit comments

Comments
 (0)