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