Skip to content
Merged
Changes from 2 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
29 changes: 29 additions & 0 deletions best-time-to-buy-and-sell-stock/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
Constraints:
1. 1 <= prices.length <= 10^5
2. 0 <= prices[i] <= 10^4

Time Complexity: O(n)

Space Complexity: O(1)

풀이 방법:
- 배열을 한 번 순회하면서:
1. 현재까지의 최소 가격(min_price)을 계속 갱신
2. 현재 가격에서 최소 가격을 뺀 값(현재 가능한 이익)과 기존 최대 이익을 비교하여 더 큰 값을 저장
- 이 방식으로 각 시점에서 가능한 최대 이익을 계산함

To Do:
- 다른 접근 방법 찾아보기 (Two Pointers, Dynamic Programming)
Copy link
Contributor

Choose a reason for hiding this comment

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

다른 접근 방법(Two Pointers, Dynamic Programming)을 고려해 보라고 주석에 적혀 있는데, 이 코드와 비교했을 때 어떤 장단점이 있을까요?

Copy link
Contributor

Choose a reason for hiding this comment

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

@lledellebell 제약조건이 추가되었을 때를 고려해볼 수 있을 것 같습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@EgonD3V 조금 늦었지만, 답변 감사합니다!

"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = prices[0]
max_profit = 0

for i in range(1, len(prices)):
min_price = min(min_price, prices[i])
max_profit = max(max_profit, prices[i] - min_price)

return max_profit

Loading