-
-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: solve #221 Best Time to Buy And Sell Stock with ts
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |