Skip to content

Commit f47870c

Browse files
committed
Solution: Maximum Product Subarray
1 parent 9aee332 commit f47870c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* ํ’€์ด
3+
* - ์ฃผ์–ด์ง„ ๋ฐฐ์—ด `nums`๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ์กฐํšŒํ•ฉ๋‹ˆ๋‹ค
4+
* - 0๊ณผ ์Œ์ˆ˜๋ฅผ ๊ณฑํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜๊ธฐ ์œ„ํ•ด ํ˜„์žฌ subarray์˜ ๊ณฑ์˜ ์ตœ๋Œ€๊ฐ’๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ตœ์†Œ๊ฐ’ ๋˜ํ•œ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค
5+
*
6+
* Big-O
7+
* - N: ์ฃผ์–ด์ง„ ๋ฐฐ์—ด `nums`์˜ size
8+
*
9+
* - Time complexity: O(N)
10+
* - Space complexity: O(1)
11+
*/
12+
13+
class Solution {
14+
public:
15+
int maxProduct(vector<int>& nums) {
16+
int max_prod = nums[0];
17+
int min_prod = nums[0];
18+
int res = nums[0];
19+
20+
for (int i = 1; i < nums.size(); i++) {
21+
int curr = nums[i];
22+
23+
int tmp_max = max(curr, max(curr * max_prod, curr * min_prod));
24+
min_prod = min(curr, min(curr * max_prod, curr * min_prod));
25+
max_prod = tmp_max;
26+
27+
res = max(res, max_prod);
28+
}
29+
30+
return res;
31+
}
32+
};

0 commit comments

Comments
ย (0)