Skip to content

Commit c4f616e

Browse files
committed
feat(soobing): week9 > maximum-product-subarray
1 parent 5441051 commit c4f616e

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* 문제 설명
3+
* - 배열에서 연속된 부분 배열의 곱이 가장 큰 값을 찾는 문제
4+
*
5+
* 아이디어
6+
* - 1) 브루트포스 O(n^2)
7+
* - 2) DP 최적화 O(n)
8+
* - 매 index마다, 현재까지 max 곱, min 곱을 찾고 최대값을 갱신
9+
*/
10+
function maxProduct(nums: number[]): number {
11+
let maxSoFar = nums[0];
12+
let max = nums[0];
13+
let min = nums[0];
14+
15+
for (let i = 1; i < nums.length; i++) {
16+
const candidate = [nums[i], max * nums[i], min * nums[i]];
17+
max = Math.max(...candidate);
18+
min = Math.min(...candidate);
19+
maxSoFar = Math.max(maxSoFar, max);
20+
}
21+
return maxSoFar;
22+
}

0 commit comments

Comments
 (0)