File tree Expand file tree Collapse file tree
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ /**
3+ * ์ค๋ ์ฃผ์์ ํ๋งคํ๋ค๊ณ ๊ฐ์ ํ๋ฉด,
4+ * ์ด์ ๋ ์ง ์ค ๊ฐ์ฅ ๋ฎ์ ๊ฐ๊ฒฉ์ ๊ตฌ๋งคํ์ ๋ ์ต๋ ์ด์ต์ ์ป์ ์ ์๋ค.
5+ * ๋ฐฐ์ด์ ์ํํ๋ฉด์ ์ต์ ๊ฐ๊ฒฉ๊ณผ ์ต๋ ์ด์ต์ ๊ณ์ ๊ฐฑ์ ํ๋ค.
6+ *
7+ * ์๊ฐ ๋ณต์ก๋: O(n)
8+ * ๊ณต๊ฐ ๋ณต์ก๋: O(1)
9+ */
10+ public int maxProfit (int [] prices ) {
11+ // ํ์ฌ๊น์ง ํ์ธํ ๋ ์ง ์ค ๊ฐ์ฅ ๋ฎ์ ์ฃผ๊ฐ
12+ int minPrice = prices [0 ];
13+
14+ // ํ์ฌ๊น์ง ์ป์ ์ ์๋ ์ต๋ ์ด์ต
15+ int maxProfit = 0 ;
16+
17+ // ์ฒซ ๋ฒ์งธ ๊ฐ๊ฒฉ์ minPrice๋ก ์ฌ์ฉํ์ผ๋ฏ๋ก ๋ ๋ฒ์งธ ๊ฐ๊ฒฉ๋ถํฐ ํ์ธํ๋ค.
18+ for (int i = 1 ; i < prices .length ; i ++) {
19+ int currentPrice = prices [i ];
20+ int currentProfit = currentPrice - minPrice ;
21+
22+ // ์ด์ ์ต์ ๊ฐ์ ๊ตฌ๋งคํ๊ณ ํ์ฌ ๊ฐ๊ฒฉ์ ํ๋งคํ์ ๋์ ์ด์ต์ ๋น๊ตํ๋ค.
23+ maxProfit = Math .max (maxProfit , currentProfit );
24+
25+ // ์ดํ ๋ ์ง์ ๊ณ์ฐ์ ์ํด ์ง๊ธ๊น์ง์ ์ต์ ๊ฐ๋ฅผ ๊ฐฑ์ ํ๋ค.
26+ minPrice = Math .min (minPrice , currentPrice );
27+ }
28+
29+ return maxProfit ;
30+ }
31+ }
You canโt perform that action at this time.
0 commit comments