File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * ์๊ฐ ๋ณต์ก๋ O(n)
3
+ * ๊ณต๊ฐ ๋ณต์ก๋ O(1)
4
+ *
5
+ * ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ
6
+ * ํ์ฌ๊น์ง์ ์ต์ ๊ฐ๊ฒฉ์ ๊ธฐ์ตํ๊ณ , ๊ทธ ๊ฐ๊ฒฉ์ ์์ ๋์ ์ด์ต์ ๊ณ์ ๊ณ์ฐํ์ฌ ์ต๋ ์ด์ต์ ๊ตฌํจ
7
+ */
8
+
9
+ /**
10
+ * @param {number[] } prices
11
+ * @return {number }
12
+ */
13
+ var maxProfit = function ( prices ) {
14
+ let minPrice = prices [ 0 ] ; // ์ต์ ๊ฐ๊ฒฉ ์ด๊ธฐํ (์ฒซ ๋ ๊ฐ๊ฒฉ)
15
+ let maxProfit = 0 ; // ์ต๋ ์ด์ต ์ด๊ธฐํ (์์ง ์ด์ต ์์)
16
+
17
+ // ๋ ๋ฒ์งธ ๋ ๋ถํฐ
18
+ for ( let i = 1 ; i < prices . length ; i ++ ) {
19
+ // ํ์ฌ ๊ฐ๊ฒฉ์ด ์ต์ ๊ฐ๊ฒฉ๋ณด๋ค ๋ฎ์ผ๋ฉด ์ต์ ๊ฐ๊ฒฉ ์
๋ฐ์ดํธ
20
+ if ( prices [ i ] < minPrice ) {
21
+ minPrice = prices [ i ] ;
22
+ }
23
+ // ํ์ฌ ๊ฐ๋ฅํ ์ด์ต ๊ณ์ฐ (ํ์ฌ ๊ฐ๊ฒฉ - ์ต์ ๊ฐ๊ฒฉ)
24
+ const currentProfit = prices [ i ] - minPrice ;
25
+
26
+ // ์ต๋ ์ด์ต ์
๋ฐ์ดํธ
27
+ if ( currentProfit > maxProfit ) {
28
+ maxProfit = currentProfit ;
29
+ }
30
+ }
31
+
32
+ return maxProfit ;
33
+ } ;
You canโt perform that action at this time.
0 commit comments