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
29 changes: 29 additions & 0 deletions best-time-to-buy-and-sell-stock/taewanseoul.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* 121. Best Time to Buy and Sell Stock
* You are given an array prices where prices[i] is the price of a given stock on the ith day.
* You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
* Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
*
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
*/

// O(n) time
// O(n) space
Copy link
Contributor

Choose a reason for hiding this comment

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

사용하는 변수는 highestProfit, left, right 3개로, 입력값의 크기와 관계없이 메모리 사용량이 일정하므로
공간 복잡도는 O(1)이 되지 않을까요?

Copy link
Contributor Author

@taewanseoul taewanseoul Jan 9, 2025

Choose a reason for hiding this comment

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

아 그렇네요. 확인 감사합니다~

function maxProfit(prices: number[]): number {
let highestProfit = 0;
let left = 0;
let right = 1;

while (right < prices.length) {
if (prices[left] < prices[right]) {
let profit = prices[right] - prices[left];
highestProfit = Math.max(highestProfit, profit);
} else {
left = right;
}

right++;
}

return highestProfit;
}
Loading