forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtolluset.ts
More file actions
39 lines (29 loc) Β· 692 Bytes
/
tolluset.ts
File metadata and controls
39 lines (29 loc) Β· 692 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
28
29
30
31
32
33
34
35
36
37
38
39
/*
* TC: O(n)
* SC: O(1)
* */
function maxProduct(nums: number[]): number {
const n = nums.length;
if (n === 1) {
return nums[0];
}
let max = 0,
min = 0,
res = 0;
for (let i = 0; i < n; i++) {
const cur = nums[i];
if (cur < 0) {
[max, min] = [min, max];
}
max = Math.max(cur, max * cur);
min = Math.min(cur, min * cur);
res = Math.max(res, max);
}
return res;
}
const t1 = maxProduct([2, 3, -2, 4]);
console.info("π : tolluset.ts:3: t1=", t1); // 6
const t2 = maxProduct([-2, 0, -1]);
console.info("π : tolluset.ts:6: t2=", t2); // 0
const t3 = maxProduct([-2]);
console.info("π : tolluset.ts:34: t3=", t3); // -2