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
24 changes: 24 additions & 0 deletions best-time-to-buy-and-sell-stock/dohyeon2.java
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,24 @@
class Solution {
// TC : O(n)
// SC : O(1)
public int maxProfit(int[] prices) {
int maximumProfit = 0;
int cursor = 0;

// 전체를 순회하면서 이익을 검증
for(int i = 0; i < prices.length; i++){
int profit = prices[i] - prices[cursor];

// 만약 현재 값이 커서의 값보다 더 작다면 현재 값부터 비교하기 시작
if(profit < 0){
cursor = i;
continue;
}

// 이전에 커서로 추정한 값이 높더라도 Math.max로 보존됨
maximumProfit = Math.max(profit, maximumProfit);
}

return maximumProfit;
}
}
Loading