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

maximum-product-subarray/flynn.cpp

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)