Skip to content

Commit 9d90baa

Browse files
committed
maximum-product-subarray solution
1 parent 76c9478 commit 9d90baa

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param nums - 정수 배열
3+
* @returns - 정수 배열의 부분 배열의 곱이 가장 큰 값을 반환
4+
* @description
5+
* - 값이 음수일 경우 최솟값과 곱해 최댓값을 도출 할 수 있으므로 swap
6+
* - min, max를 현재 값과 비교하며 변경
7+
*/
8+
9+
function maxProduct(nums: number[]): number {
10+
let maximum = nums[0];
11+
let minimum = nums[0];
12+
let result = nums[0];
13+
14+
for (let i = 1; i < nums.length; i++) {
15+
const current = nums[i];
16+
17+
if (current < 0) {
18+
let temp = maximum;
19+
maximum = minimum;
20+
minimum = temp;
21+
}
22+
23+
maximum = Math.max(current, current * maximum);
24+
minimum = Math.min(current, current * minimum);
25+
26+
result = Math.max(result, maximum);
27+
}
28+
29+
return result;
30+
}
31+
32+
const nums = [-2, 3, -4];
33+
34+
maxProduct(nums);
35+
36+
37+

0 commit comments

Comments
 (0)