We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5003c24 commit 1381be3Copy full SHA for 1381be3
best-time-to-buy-and-sell-stock/gmlwls96.kt
@@ -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