File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * ์ ์ ๋ฐฐ์ด์์ ์ฐ์๋ ๋ถ๋ถ๋ฐฐ์ด(subarray)์ ๊ณฑ์ด ์ต๋๊ฐ ๋๋ ๊ฐ์ ์ฐพ๋ ํจ์
3
+ *
4
+ * ์์๋ผ๋ฆฌ ๊ณฑํ๋ฉด ์์๊ฐ ๋จ
5
+ * 0์ด ๋์ค๋ฉด ๊ณฑ์ 0์ด ๋จ => ๋ถ๋ถ๋ฐฐ์ด์ ์๋ก ์์ํด์ผ ํจ
6
+ * ์ต๋๊ฐ๊ณผ ์ต์๊ฐ์ ๋์์ ์ถ์ ํด์ผ ํจ: ์์์ ๊ฒฝ์ฐ ์ต๋๊ฐ์ด ์ต์๊ฐ์ด ๋ ์ ์์
7
+ *
8
+ * ์ ๊ทผ ๋ฐฉ๋ฒ: ๋์ ํ๋ก๊ทธ๋๋ฐ
9
+ * ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(1)
10
+ */
11
+
12
+ /**
13
+ * @param {number[] } nums
14
+ * @return {number }
15
+ */
16
+ var maxProduct = function ( nums ) {
17
+ if ( nums . length === 0 ) return 0 ;
18
+
19
+ // ํ์ฌ ์์น์์ ๋๋๋ ๋ถ๋ถ๋ฐฐ์ด์ ์ต๋๊ณฑ๊ณผ ์ต์๊ณฑ
20
+ let maxHere = nums [ 0 ] ;
21
+ let minHere = nums [ 0 ] ;
22
+ let result = nums [ 0 ] ;
23
+
24
+ for ( let i = 1 ; i < nums . length ; i ++ ) {
25
+ const num = nums [ i ] ;
26
+
27
+ // ํ์ฌ ์ซ์๊ฐ ์์๋ผ๋ฉด max์ min์ด ๋ฐ๋ ์ ์์
28
+ if ( num < 0 ) {
29
+ [ maxHere , minHere ] = [ minHere , maxHere ] ;
30
+ }
31
+
32
+ // ํ์ฌ ์ซ์๋ถํฐ ์๋ก ์์ํ๊ฑฐ๋, ๊ธฐ์กด ๊ณฑ์ ํ์ฌ ์ซ์๋ฅผ ๊ณฑํจ
33
+ maxHere = Math . max ( num , maxHere * num ) ;
34
+ minHere = Math . min ( num , minHere * num ) ;
35
+
36
+ // ์ ์ฒด ์ต๋๊ฐ ์
๋ฐ์ดํธ
37
+ result = Math . max ( result , maxHere ) ;
38
+ }
39
+
40
+ return result ;
41
+ } ;
You canโt perform that action at this time.
0 commit comments