Skip to content

Commit 9b971eb

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
best time to buy and sell stock
1 parent d52bb73 commit 9b971eb

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
ย (0)