Skip to content
Merged
Changes from all commits
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
19 changes: 19 additions & 0 deletions best-time-to-buy-and-sell-stock/bus710.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

package hello

func maxProfit(prices []int) int {
min := prices[0]
maxProfit := 0

for i := 1; i < len(prices); i++ {
if prices[i] < min {
min = prices[i]
}
if (prices[i] - min) > maxProfit {
maxProfit = prices[i] - min
}
}
Comment on lines +5 to +16
Copy link
Contributor

Choose a reason for hiding this comment

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

공간 복잡도는 말씀해주신 대로 상수 크기 변수만 사용하니까 빅오 표기법에 따라 O(1)이 될 거 같아요.
그리고 리트코드의 효율성 분석을 그대로 믿을 수 없다.. 는 글을 어디서 본 것 같아요.
저도 지금 이 코드 그대로 돌려봤는데 메모리가 10% 나오는 걸 보니 맞는 것 같고요.

지금 코드도 충분히 최적화되어 있는 듯한데요.
13번 라인에 else if 처리를 하면 불필요한 연산이 조금 줄 것 같습니다.
prices[i] < min이면 prices[i] - min이 음수가 되어서 maxProfit을 업데이트해줄 필요가 없을 거 같아요.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

그렇네요 브랜치 하나 더 줄일 수 있겠네요...!


return maxProfit
}
Loading