Skip to content

Commit cb616a0

Browse files
authored
[ PS ] : Maximum Product Subarray
1 parent dc454f5 commit cb616a0

File tree

1 file changed

+23
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)