Skip to content

Commit 1381be3

Browse files
committed
[Week5](gmlwls96) Best time to buy an sell stock
1 parent 5003c24 commit 1381be3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
/**
3+
* 시간 : O(n) 공간 : O(1)
4+
* 풀이
5+
* lastIndex - 1부터 0까지 조회하면서 가장높은값(maxPrice) 에서 현재값(price[i])의 차(currentProfit)를 구한다.
6+
* profit 과 currentProfit중 더 높은값이 profit.
7+
* maxPrice와 prices[i]중 더 높은값이 maxPrice가 된다.
8+
* */
9+
fun maxProfit(prices: IntArray): Int {
10+
var profit = 0
11+
var maxPrice = prices[prices.lastIndex]
12+
for (i in prices.lastIndex - 1 downTo 0) {
13+
val currentProfit = maxPrice - prices[i]
14+
profit = max(profit, currentProfit)
15+
maxPrice = max(maxPrice, prices[i])
16+
}
17+
18+
return profit
19+
}
20+
}

0 commit comments

Comments
 (0)