Skip to content

Commit 3cdce51

Browse files
add post '(Leetcode) 152 - Maximum Product Subarray 풀이'
1 parent f32cb1b commit 3cdce51

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

_posts/2024-07-09-leetcode-152.md

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 152 - Maximum Product Subarray 풀이
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, array, subarray, product]
6+
date: 2024-07-09 16:30:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/maximum-product-subarray/](https://leetcode.com/problems/maximum-product-subarray/)
17+
18+
## 내가 작성한 풀이
19+
20+
그냥 모든 케이스를 고려하여 코드를 작성하였다.
21+
22+
다음과 같은 부분들을 고려했다.
23+
24+
- 0 을 만나면 구간이 끊킨다.
25+
- 음수를 만나더라도 다음 음수를 만나면 양수가 될 수 있다.
26+
- 음수를 만났을 때 다음 음수가 없다면, 이전 부분은 더 이상 쓸모가 없다.
27+
28+
```java
29+
class Solution {
30+
public int maxProduct(int[] nums) {
31+
int max = Integer.MIN_VALUE;
32+
int temp = 0;
33+
int lastZeroIndex = 0;
34+
for (int i = 0; i < nums.length; i++) {
35+
int current = nums[i];
36+
if (temp == 0) {
37+
temp = current;
38+
lastZeroIndex = i;
39+
} else {
40+
if (current == 0) {
41+
temp = 0;
42+
} else if (temp > 0 && current < 0) {
43+
if (hasNextMinus(nums, i + 1)) {
44+
temp = temp * current;
45+
} else {
46+
temp = temp * current;
47+
for (int j = lastZeroIndex; j < i + 1; j++) {
48+
temp = temp / nums[j];
49+
if (temp > 0) {
50+
break;
51+
}
52+
}
53+
}
54+
} else {
55+
temp = temp * current;
56+
}
57+
}
58+
max = Math.max(max, temp);
59+
if (temp < 0 && !hasNextMinus(nums, i + 1)) {
60+
temp = 0;
61+
}
62+
}
63+
return max;
64+
}
65+
66+
private boolean hasNextMinus(int[] nums, int i) {
67+
for (; i < nums.length; i++) {
68+
if (nums[i] < 0) {
69+
return true;
70+
} else if (nums[i] == 0) {
71+
return false;
72+
}
73+
}
74+
return false;
75+
}
76+
}
77+
```
78+
79+
### TC, SC
80+
81+
시간 복잡도는 O(n^2)이다. 공간 복잡도는 O(1)이다. hasNextMinus 이 적게 호출된다면 시간 복잡도는 O(n)에 가깝게 동작한다.
82+
83+
![submit result](/assets/images/2024-07-09-leetcode-152/submit_result.png)
84+
85+
beat 93.31%
Loading

0 commit comments

Comments
 (0)