File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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)์ ๊ฐ๊น๊ฒ ๋์ํ๋ค.
You canโt perform that action at this time.
0 commit comments