Skip to content

Commit

Permalink
add: solve #221 Best Time to Buy And Sell Stock with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yjason-K committed Jan 4, 2025
1 parent 07fa579 commit fcf70c9
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions best-time-to-buy-and-sell-stock/Yjason-K.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* ์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜
* @param {number[]} prices
* @returns {number}
*
* ์‹œ๊ฐ„ ๋ณต์žก๋„ : O(n) (n: ์ฃผ์‹ ๊ฐ€๊ฒฉ ๋ฐฐ์—ด์˜ ๊ธธ์ด)
* ๊ณต๊ฐ„ ๋ณต์žก๋„ : 0(1) (์ถ”๊ฐ€ ์ž๋ฃŒ๊ตฌ์กฐ X)
*/
function maxProfit(prices: number[]): number {
let minPrice = 100001; // ์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ์†Œ ๊ฐ€๊ฒฉ
let maxProfit = 0; // ์ตœ๋Œ€ ์ด์ต

for (let price of prices) {
// ์ตœ์†Œ ๊ฐ€๊ฒฉ ๊ฐฑ์‹ 
if (price < minPrice) {
minPrice = price;
}

// ํ˜„์žฌ ๊ฐ€๊ฒฉ์—์„œ ์ตœ์†Œ ๊ฐ€๊ฒฉ์„ ๋บ€ ์ด์ต์ด ์ตœ๋Œ€ ์ด์ต๋ณด๋‹ค ํฌ๋‹ค๋ฉด ๊ฐฑ์‹ 
const potentialProfit = price - minPrice;
if (potentialProfit > maxProfit) {
maxProfit = potentialProfit;
}
}

return maxProfit;
}

0 comments on commit fcf70c9

Please sign in to comment.