Skip to content

Commit 284e10e

Browse files
committed
maximum-product-subarray
1 parent 66c3e3a commit 284e10e

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var maxProduct = function (nums) {
6+
let answer = nums[0];
7+
let max = 1;
8+
let min = 1;
9+
10+
for (let i = 0; i < nums.length; i++) {
11+
const current = nums[i];
12+
13+
const candidates = [max * current, min * current, current];
14+
15+
max = Math.max(...candidates);
16+
min = Math.min(...candidates);
17+
answer = Math.max(answer, max);
18+
}
19+
20+
return answer;
21+
};
22+
23+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(n) * O(8) -> nums์˜ ๊ธธ์ด ๋งŒํผ์„ for ๋ฌธ์œผ๋กœ ์ˆœํ™˜ํ•˜๋ฉด์„œ Mathํด๋ž˜์Šค์˜ max, min๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœ(์ธ์ž๊ฐ€ 3๊ฐœ, 3๊ฐœ, 2๊ฐœ ์ด๋ฏ€๋กœ ์ด 8ํšŒ ์ˆœํšŒ)
24+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(1) -> ํŒŒ๋ผ๋ฏธํ„ฐ nums์— ๋Œ€ํ•ด ์˜๋ฏธ์žˆ๋Š” ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๋Š” ๋ณ€์ˆ˜ํ• ๋‹น์ด ์—†์Œ

0 commit comments

Comments
ย (0)