Skip to content

Commit 55d8a16

Browse files
committed
add Maximum Product Subarray solution
1 parent 96a024a commit 55d8a16

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* [Problem]: [152] Maximum Product Subarray
3+
* (https://leetcode.com/problems/maximum-product-subarray/description/)
4+
*/
5+
function maxProduct(nums: number[]): number {
6+
// 시간복잡도 O(n^2)
7+
// 공간복잡도 O(1)
8+
function bruteForce(nums: number[]): number {
9+
let maxProduct = nums[0];
10+
11+
for (let i = 0; i < nums.length; i++) {
12+
let product = 1;
13+
for (let j = i; j < nums.length; j++) {
14+
product *= nums[j];
15+
maxProduct = Math.max(maxProduct, product);
16+
}
17+
}
18+
19+
return maxProduct;
20+
}
21+
22+
// 시간복잡도 O(n)
23+
// 공간복잡도 O(1)
24+
function optimizedFunc(nums: number[]): number {
25+
let maxResult = nums[0];
26+
let minResult = nums[0];
27+
let result = nums[0];
28+
29+
for (let i = 1; i < nums.length; i++) {
30+
const num = nums[i];
31+
32+
if (num < 0) {
33+
[maxResult, minResult] = [minResult, maxResult];
34+
}
35+
36+
maxResult = Math.max(num, num * maxResult);
37+
minResult = Math.min(num, num * minResult);
38+
result = Math.max(result, maxResult);
39+
}
40+
41+
return result;
42+
}
43+
}

0 commit comments

Comments
 (0)