Skip to content

Commit fe3e282

Browse files
Jeehay28Jeehay28
authored andcommitted
Add maximum-product-subarray solution in TS
1 parent 9ec8965 commit fe3e282

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// TC: O(n)
2+
// SC: O(1)
3+
function maxProduct(nums: number[]): number {
4+
let prevMax = nums[0];
5+
let prevMin = nums[0];
6+
let maxProd = nums[0];
7+
8+
for (let i = 1; i < nums.length; i++) {
9+
const currentNum = nums[i];
10+
const tempMax = Math.max(
11+
currentNum,
12+
prevMax * currentNum,
13+
prevMin * currentNum
14+
);
15+
prevMin = Math.min(currentNum, prevMax * currentNum, prevMin * currentNum);
16+
prevMax = tempMax;
17+
maxProd = Math.max(maxProd, prevMax);
18+
}
19+
20+
return maxProd;
21+
}
22+
23+
24+
// TC: O(n^2)
25+
// SC: O(1)
26+
// function maxProduct(nums: number[]): number {
27+
// let largestProd = -Infinity;
28+
// let subProd = 1;
29+
30+
// for (let i = 0; i < nums.length; i++) {
31+
// subProd = 1;
32+
// for (let j = i; j < nums.length; j++) {
33+
// subProd *= nums[j];
34+
// largestProd = Math.max(largestProd, subProd);
35+
// }
36+
// }
37+
38+
// return largestProd;
39+
// }
40+

0 commit comments

Comments
 (0)