File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * ν΅μ¬ μμ΄λμ΄:
3+ * μ΄λ€ λ μ μ£Όμμ ν λ μ΅λ μ΄μ΅μ μ»μΌλ €λ©΄,
4+ * κ·Έ λ μ΄μ μ μ΅μ κ°μ μμ΄μΌ νλ€.
5+ * λ°λΌμ λ°°μ΄μ μννλ©΄μ "μ§κΈκΉμ§μ μ΅μ κ°"λ§ μΆμ νκ³ ,
6+ * λ§€ μμ λ§λ€ (νμ¬κ° - μ΅μ κ°)λ‘ μ μ¬ μ΄μ΅μ κ³μ°νλ©΄ λλ€.
7+ *
8+ * μκ° λ³΅μ‘λ: O(n) - λ°°μ΄μ ν λ²λ§ μν
9+ * κ³΅κ° λ³΅μ‘λ: O(1) - λ³μ 2κ°λ§ μ¬μ©
10+ */
11+ const maxProfit = ( prices ) => {
12+ let minPrice = prices [ 0 ] ;
13+ let maxProfit = 0 ;
14+
15+ for ( let i = 1 ; i < prices . length ; i ++ ) {
16+ const price = prices [ i ] ;
17+ if ( price < minPrice ) {
18+ minPrice = price ;
19+ } else if ( price - minPrice > maxProfit ) {
20+ maxProfit = price - minPrice ;
21+ }
22+ }
23+
24+ return maxProfit ;
25+ } ;
You canβt perform that action at this time.
0 commit comments