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
21 changes: 21 additions & 0 deletions best-time-to-buy-and-sell-stock/sadie100.ts
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

  • 패턴: Greedy
  • 설명: 이 코드는 매번 현재 가격과 이전 최저 가격을 비교하여 최대 이익을 갱신하는 방식으로, 최적의 선택을 하는 그리디 알고리즘 패턴에 속합니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
prices를 순회하며 현재 최저값과의 차이를 구해서 최대 profit을 갱신한 뒤 최저값(구매가)를 갱신, 최종값을 리턴한다

시간복잡도 O(N) - N은 prices의 length
*/

function maxProfit(prices: number[]): number {
let buy
let result = 0

for (let price of prices) {
if (buy === undefined) {
buy = price
continue
}
result = Math.max(result, price - buy)
buy = Math.min(price, buy)
}

return result
}
Loading