1
+ import java .util .ArrayList ;
2
+ import java .util .List ;
3
+
4
+ // 답지보고 풀이..
5
+ class Solution {
6
+ public int maxProduct (int [] nums ) {
7
+ int max = nums [0 ];
8
+ int currMax = nums [0 ];
9
+ int currMin = nums [0 ];
10
+
11
+ for (int i = 1 ; i < nums .length ; i ++) {
12
+ int temp = currMax ;
13
+ currMax = Math .max (nums [i ], Math .max (currMax * nums [i ], currMin * nums [i ]));
14
+ currMin = Math .min (nums [i ], Math .min (temp * nums [i ], currMin * nums [i ]));
15
+ max = Math .max (max , currMax );
16
+ }
17
+
18
+ return max ;
19
+ }
20
+ }
21
+
22
+ // NOTE:핵심 컨셉은 0을 만나기 전까지 한칸씩 늘려가며 모든 원소의 곱을 만든다. 0을 만나면 첫 번째 원소를 뺀 나머지 원소들의 곱의
23
+ // 값으로 최대값을 계속 갱신해나간다.
24
+ class WrongSolution {
25
+
26
+ public int mx = -98764321 ;
27
+ public List <Boolean > bList = new ArrayList <>();
28
+ public boolean isStartInit = true ;
29
+ public boolean isOverZero = false ;
30
+
31
+ public int maxProduct (int [] nums ) {
32
+ int start = 1 ;
33
+ int zeroIdx = 0 ;
34
+ if (nums .length == 1 ) {
35
+ return nums [0 ];
36
+ }
37
+
38
+ for (int i = 0 ; i < nums .length ; i ++) {
39
+
40
+ if (nums [i ] == 0 ) {
41
+ if (mx <= 0 ) {
42
+ bList .add (false );
43
+ } else {
44
+ bList .add (true );
45
+ }
46
+
47
+ while (zeroIdx < i ) {
48
+ start /= nums [zeroIdx ];
49
+ mx = Math .max (mx , start );
50
+
51
+ if (mx >= 1 ) {
52
+ bList .add (true );
53
+ }
54
+
55
+ zeroIdx ++;
56
+ }
57
+
58
+ start = 1 ;
59
+ isStartInit = true ;
60
+ zeroIdx ++; // 0값인 인덱스를 건너뛰고 다음 번 인덱스를 대입
61
+ } else {
62
+ start *= nums [i ];
63
+ mx = Math .max (mx , start );
64
+
65
+ if (start >= 1 ) {
66
+ isStartInit = false ;
67
+ isOverZero = true ;
68
+ }
69
+ }
70
+ }
71
+
72
+ while (zeroIdx < nums .length ) {
73
+ start /= nums [zeroIdx ];
74
+ mx = Math .max (mx , start );
75
+ zeroIdx ++;
76
+ }
77
+
78
+ mx = Math .max (mx , nums [nums .length - 1 ]);
79
+
80
+ if (nums [nums .length - 1 ] >= 1 ) {
81
+ isOverZero = true ;
82
+ }
83
+
84
+ if (mx > 0 && isOverZero ) {
85
+ bList .add (true );
86
+ }
87
+
88
+ for (boolean b : bList ) {
89
+ if (b ) {
90
+ return mx ;
91
+ }
92
+ }
93
+
94
+ if (bList .size () > 0 ) {
95
+ return isStartInit ? 0 : mx ;
96
+ }
97
+
98
+ return mx ;
99
+ }
100
+ }
0 commit comments