Skip to content

Commit d6fc961

Browse files
committed
solve: maximum subarray
1 parent 8a907ea commit d6fc961

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

maximum-subarray/tolluset.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function maxProduct(nums: number[]): number {
2+
const n = nums.length;
3+
4+
if (n === 1) {
5+
return nums[0];
6+
}
7+
8+
let max = 0,
9+
min = 0,
10+
res = 0;
11+
12+
for (let i = 0; i < n; i++) {
13+
const cur = nums[i];
14+
15+
if (cur < 0) {
16+
[max, min] = [min, max];
17+
}
18+
19+
max = Math.max(cur, max * cur);
20+
min = Math.min(cur, min * cur);
21+
22+
res = Math.max(res, max);
23+
}
24+
25+
return res;
26+
}
27+
28+
const t1 = maxProduct([2, 3, -2, 4]);
29+
console.info("🚀 : tolluset.ts:3: t1=", t1); // 6
30+
31+
const t2 = maxProduct([-2, 0, -1]);
32+
console.info("🚀 : tolluset.ts:6: t2=", t2); // 0
33+
34+
const t3 = maxProduct([-2]);
35+
console.info("🚀 : tolluset.ts:34: t3=", t3); // -2

0 commit comments

Comments
 (0)