Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions best-time-to-buy-and-sell-stock/sonjh1217.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
var maxProfit = 0
var minPrice = prices[0]

for i in (1..<prices.count) {
let profit = prices[i] - minPrice
maxProfit = max(profit, maxProfit)
Comment on lines +7 to +8
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minPrice가 prices[i]보다 큰 경우에만 minPrice를 업데이트 하면 어떨까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If minPrice > prices[I] {
minPrice = prices[I]
}

요런 방식이 되겠네요! 사실 그러면 maxProfit = max(profit, maxProfit) 이 부분 역시
if profit > maxProfit {
maxProfit = profit
}

이렇게 될텐데요! 이 변경이 복잡도를 개선하는 것은 아니고, 업데이트를 덜 치기 때문에 약간 더 효율적이지만 min과 max가 주는 가독성이 저는 더 좋게 느껴져서 min, max 방식을 유지하려고 합니다. 디테일한 피드백 넘 감사합니다!

minPrice = min(prices[i], minPrice)
}

return maxProfit

//시간복잡도 O(n)
//공간복잡도 O(1)
}
}