Skip to content

Commit 38fa297

Browse files
week11 mission maximum-product-subarray
1 parent 681171a commit 38fa297

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
- ๋ฌธ์ œ: https://leetcode.com/problems/maximum-product-subarray/
2+
- ํ’€์ด: https://algorithm.jonghoonpark.com/2024/07/09/leetcode-152
3+
4+
```java
5+
class Solution {
6+
public int maxProduct(int[] nums) {
7+
int max = Integer.MIN_VALUE;
8+
int temp = 0;
9+
int lastZeroIndex = 0;
10+
for (int i = 0; i < nums.length; i++) {
11+
int current = nums[i];
12+
if (temp == 0) {
13+
temp = current;
14+
lastZeroIndex = i;
15+
} else {
16+
if (current == 0) {
17+
temp = 0;
18+
} else if (temp > 0 && current < 0) {
19+
if (hasNextMinus(nums, i + 1)) {
20+
temp = temp * current;
21+
} else {
22+
temp = temp * current;
23+
for (int j = lastZeroIndex; j < i + 1; j++) {
24+
temp = temp / nums[j];
25+
if (temp > 0) {
26+
break;
27+
}
28+
}
29+
}
30+
} else {
31+
temp = temp * current;
32+
}
33+
}
34+
max = Math.max(max, temp);
35+
if (temp < 0 && !hasNextMinus(nums, i + 1)) {
36+
temp = 0;
37+
}
38+
}
39+
return max;
40+
}
41+
42+
private boolean hasNextMinus(int[] nums, int i) {
43+
for (; i < nums.length; i++) {
44+
if (nums[i] < 0) {
45+
return true;
46+
} else if (nums[i] == 0) {
47+
return false;
48+
}
49+
}
50+
return false;
51+
}
52+
}
53+
```
54+
55+
### TC, SC
56+
57+
์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n^2)์ด๋‹ค. ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(1)์ด๋‹ค. hasNextMinus ์ด ์ ๊ฒŒ ํ˜ธ์ถœ๋œ๋‹ค๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n)์— ๊ฐ€๊น๊ฒŒ ๋™์ž‘ํ•œ๋‹ค.

0 commit comments

Comments
ย (0)