File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ /*
4+ * ๋ ๊ฑฐ๋์ผ ์ฌ์ด ์ต๊ณ ์ ์์ต์ ๊ตฌํ๋ ๋ฌธ์
5+ * ์๊ฐ ๋ณต์ก๋: O(n^2)
6+ * -> ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ์ํํ๋ฉฐ ๊ฑฐ๋์ผ ์ฌ์ด ์ต๊ณ ๊ฐ๊ฒฉ์ ๊ตฌํ๋ ๋ก์ง: O(n^2)
7+ * ๊ณต๊ฐ ๋ณต์ก๋: O(1)
8+ * ์๋ ๋ก์ง์ ์๊ฐ ์ด๊ณผ ๋ฐ์ O(n^2)์ ๋ณต์ก๋๋ฅผ ์ค์ฌ์ผํจ.
9+ * */
10+ fun maxProfit (prices : IntArray ): Int {
11+ var result = Int .MIN_VALUE
12+
13+ for (i in prices.indices) {
14+ for (j in i + 1 until prices.size) {
15+ if (prices[i] < prices[j]) {
16+ if (result < prices[j] - prices[i]) {
17+ result = prices[j] - prices[i]
18+ }
19+ }
20+ }
21+ }
22+ if (result == Int .MIN_VALUE ) return 0
23+ return result
24+ }
25+
26+ /*
27+ * ๊ฐ์ฅ ์์ ๊ฐ์ ์ ์ฅํ๋ ๋ณ์์ ๊ฐ์ฅ ํฐ ์์ต์ ๊ฐ๋ ๋ณ์๋ฅผ ๋๊ณ ๋ฌธ์ ํด๊ฒฐ
28+ * ์๊ฐ ๋ณต์ก๋: O(n)
29+ * ๊ณต๊ฐ ๋ณต์ก๋: O(1)
30+ * */
31+ fun maxProfit2 (prices : IntArray ): Int {
32+ var minValue = Int .MAX_VALUE
33+ var maxValue = 0
34+
35+ for (price in prices) {
36+ if (price < minValue) {
37+ minValue = price
38+ } else if (price - minValue > maxValue) {
39+ maxValue = price - minValue
40+ }
41+ }
42+ return maxValue
43+ }
You canโt perform that action at this time.
0 commit comments