Skip to content

[clara-shin] WEEK 05 solutions #1392

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 2, 2025
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
33 changes: 33 additions & 0 deletions best-time-to-buy-and-sell-stock/clara-shin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* 시간 복잡도 O(n)
* 공간 복잡도 O(1)
*
* 그리디 알고리즘
* 현재까지의 최저 가격을 기억하고, 그 가격에 샀을 때의 이익을 계속 계산하여 최대 이익을 구함
*/

/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let minPrice = prices[0]; // 최저 가격 초기화 (첫 날 가격)
let maxProfit = 0; // 최대 이익 초기화 (아직 이익 없음)

// 두 번째 날부터
for (let i = 1; i < prices.length; i++) {
// 현재 가격이 최저 가격보다 낮으면 최저 가격 업데이트
if (prices[i] < minPrice) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Math.min 함수를 쓰면 직관적이고, 한줄로 코드량도 줄어들것 같아요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@ayosecu
그러네요! 내장함수를 사용하니 더 간결하고 의도가 명확히 보여요 감사합니다!

minPrice = prices[i];
}
// 현재 가능한 이익 계산 (현재 가격 - 최저 가격)
const currentProfit = prices[i] - minPrice;

// 최대 이익 업데이트
if (currentProfit > maxProfit) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Math.max 함수를 쓰면 직관적이고, 한줄로 코드량도 줄어들것 같아요!

maxProfit = currentProfit;
}
}

return maxProfit;
};