Skip to content

Commit 239bfda

Browse files
committed
add maximum product subarray solution
1 parent 258b308 commit 239bfda

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
3+
// μ‹œκ°„λ³΅μž‘λ„: O(n)
4+
public int maxProduct(int[] nums) {
5+
6+
if (nums == null || nums.length == 0) {
7+
return 0;
8+
}
9+
10+
// μ΅œλŒ€ κ³± μΌ€μ΄μŠ€
11+
int maxProduct = nums[0];
12+
// μ΅œμ†Œ κ³± μΌ€μ΄μŠ€
13+
int minProduct = nums[0];
14+
// μ΅œλŒ€ κ°’
15+
int max = nums[0];
16+
17+
// DP둜 ν’€μ΄ν•˜μ˜€μ§€λ§Œ 음수 * 음수의 λ°˜λ‘€ μΌ€μ΄μŠ€ λ°œμƒν•˜μ—¬ ν•΄λ‹Ή ν’€μ΄λ‘œ μˆ˜μ •
18+
// Test Case : [-2, 3, -4] => dp둜 풀이 μ‹œ 3이 λ°˜ν™˜λ˜λŠ” 문제 μžˆμ—ˆμŒ
19+
20+
for (int i = 1; i < nums.length; i++) {
21+
22+
int current = nums[i];
23+
24+
// 음수일 경우 : μ΅œμ†Œ κ³±κ³Ό μ΅œλŒ€ κ³± μœ„μΉ˜ λ°”κΏˆ
25+
if (current < 0) {
26+
int tempMax = maxProduct;
27+
maxProduct = Math.max(current, minProduct * current);
28+
minProduct = Math.min(current, tempMax * current);
29+
} else {
30+
maxProduct = Math.max(current, maxProduct * current);
31+
minProduct = Math.min(current, minProduct * current);
32+
}
33+
34+
max = Math.max(max, maxProduct);
35+
36+
}
37+
38+
return max;
39+
40+
}
41+
}
42+

0 commit comments

Comments
Β (0)