Skip to content

Commit 97242fb

Browse files
author
eunhwa99
committed
maximum product subarray
1 parent 6060770 commit 97242fb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
3+
// TP: O(N)
4+
// SP: O(1)
5+
// ์Œ์ˆ˜ ์›์†Œ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ๊ณฑ์˜ Min ๊ฐ’๋„ ์ƒ๊ฐํ•ด์•ผ ํ–ˆ๋˜ ๋ฌธ์ œ!
6+
public int maxProduct(int[] nums) {
7+
8+
int minProd = nums[0];
9+
int maxProd = nums[0];
10+
int result = nums[0];
11+
for (int i = 1; i < nums.length; i++) {
12+
if (nums[i] < 0) {
13+
int temp = minProd;
14+
minProd = maxProd;
15+
maxProd = temp;
16+
}
17+
18+
maxProd = Math.max(nums[i], maxProd * nums[i]);
19+
minProd = Math.min(nums[i], minProd * nums[i]);
20+
result = Math.max(result, maxProd);
21+
}
22+
23+
return result;
24+
}
25+
}
26+

0 commit comments

Comments
ย (0)