Skip to content

Commit a1bf150

Browse files
committed
Maximum Product Subarray Solution
1 parent 09a3777 commit a1bf150

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* ์ •์ˆ˜ ๋ฐฐ์—ด์—์„œ ์—ฐ์†๋œ ๋ถ€๋ถ„๋ฐฐ์—ด(subarray)์˜ ๊ณฑ์ด ์ตœ๋Œ€๊ฐ€ ๋˜๋Š” ๊ฐ’์„ ์ฐพ๋Š” ํ•จ์ˆ˜
3+
*
4+
* ์Œ์ˆ˜๋ผ๋ฆฌ ๊ณฑํ•˜๋ฉด ์–‘์ˆ˜๊ฐ€ ๋จ
5+
* 0์ด ๋‚˜์˜ค๋ฉด ๊ณฑ์€ 0์ด ๋จ => ๋ถ€๋ถ„๋ฐฐ์—ด์„ ์ƒˆ๋กœ ์‹œ์ž‘ํ•ด์•ผ ํ•จ
6+
* ์ตœ๋Œ€๊ฐ’๊ณผ ์ตœ์†Œ๊ฐ’์„ ๋™์‹œ์— ์ถ”์ ํ•ด์•ผ ํ•จ: ์Œ์ˆ˜์˜ ๊ฒฝ์šฐ ์ตœ๋Œ€๊ฐ’์ด ์ตœ์†Œ๊ฐ’์ด ๋  ์ˆ˜ ์žˆ์Œ
7+
*
8+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ•: ๋™์  ํ”„๋กœ๊ทธ๋ž˜๋ฐ
9+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n), ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @return {number}
15+
*/
16+
var maxProduct = function (nums) {
17+
if (nums.length === 0) return 0;
18+
19+
// ํ˜„์žฌ ์œ„์น˜์—์„œ ๋๋‚˜๋Š” ๋ถ€๋ถ„๋ฐฐ์—ด์˜ ์ตœ๋Œ€๊ณฑ๊ณผ ์ตœ์†Œ๊ณฑ
20+
let maxHere = nums[0];
21+
let minHere = nums[0];
22+
let result = nums[0];
23+
24+
for (let i = 1; i < nums.length; i++) {
25+
const num = nums[i];
26+
27+
// ํ˜„์žฌ ์ˆซ์ž๊ฐ€ ์Œ์ˆ˜๋ผ๋ฉด max์™€ min์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ์Œ
28+
if (num < 0) {
29+
[maxHere, minHere] = [minHere, maxHere];
30+
}
31+
32+
// ํ˜„์žฌ ์ˆซ์ž๋ถ€ํ„ฐ ์ƒˆ๋กœ ์‹œ์ž‘ํ•˜๊ฑฐ๋‚˜, ๊ธฐ์กด ๊ณฑ์— ํ˜„์žฌ ์ˆซ์ž๋ฅผ ๊ณฑํ•จ
33+
maxHere = Math.max(num, maxHere * num);
34+
minHere = Math.min(num, minHere * num);
35+
36+
// ์ „์ฒด ์ตœ๋Œ€๊ฐ’ ์—…๋ฐ์ดํŠธ
37+
result = Math.max(result, maxHere);
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
ย (0)