
๐ก์๊ฐ ๋ฐฉ์
๋ฐฐ์ด์ ์ํํ๋ฉด์ ์ ์ผ ์์ ๊ฐ์ ์ ๋ฐ์ดํธํด ์ค๋ค
๊ทธ ์ดํ ๋งค์ผ ๊ทธ๋ ์ ๋ง๋ ์ฃผ์ ๊ฐ๊ฒฉ์์ ์ ์ผ ์์ ๊ฐ์ ๋นผ์ค๋ค
๊ทธ๋์ ๋ณ์ profit๋ ์ํํ๋ฉด์ ์ ์ผ ํฐ ๊ฐ์ผ๋ก ์ ๋ฐ์ดํธํด ์ค๋ค.
๐ป ์์ฑ ์ฝ๋
์์ฆ ์น ๊ฐ๋ฐ ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ๋ง์ด ๋ง์ง๋ค ๋ณด๋ ํ์ ์คํฌ๋ฆฝํธ๋ก ํ์ด๋ดค๋ค
/**
* @param {number[]} prices
* @return {number}
*/
function maxProfit(prices: number[]): number {
let profit: number = 0;
let lowestPrice: number = prices[0];
for (const price of prices) {
if (price < lowestPrice) {
lowestPrice = price;
}
profit = Math.max(profit, price - lowestPrice);
}
return profit;
}

์์งํ ๋งํด์ ์์ฆ ์ ํ๋ธ๋ก ๋ ธ์ ๋ง๋๋ ํ๋ก์ ํธ๋ฅผ ํ๋ค ๋ณด๋ ์ฝ๋ฉ ํ ์คํธ ์ค๋น์ ์กฐ๊ธ ์ํํ๋ ๊ฒ ๊ฐ๋ค
๋ฌผ๋ก ํ๋ฃจ์ ํ ๋ฌธ์ ์ฉ์ ๊พธ์คํ ํ๋ ค๊ณ ๋ ธ๋ ฅํ์ง๋ง ํ๋ฃจ ์ข ์ผ ์ฝ๋ฉ๋ง ํ๊ธฐ์ ๋๋ฌด ๋ฒ ์ฐจ์ ์ค๊ฐ์ค๊ฐ ๋นผ๋จน์ ์ ์ด ๋ง๋ค
๊ทธ๋ฆฌ๊ณ ํ์ด๋ ๋ธ๋ก๊ทธ์ ์ฌ๋ฆฌ๊ธฐ๊ฐ ๋๋ฌด ๊ท์ฐฎ์์ ์ฌ๋ฆฌ์ง ๋ชปํ๋ค
๊ทธ๋์ ํ๋ก์ ํธ๋ ๋ง๋ฌด๋ฆฌ ๋จ๊ณ์ ๋ค์ด์ฐ์ผ๋ ํ์๋ ๋ฌธ์ ๋ฅผ ์กฐ๊ธ์ฉ ๋ฆ๊ฒ๋๋ง ์ฌ๋ฆฌ๋ ค๊ณ ํ๋ค...(์ฌ๋ฆด๊ฒ ๋๋ฌด ๋ง์์ ธ๋ฒ๋ ธ๋ค...)
์กฐ๊ธ์ ํํ๋ ๋จ์ง ์๊ฒ ํ๋ฃจ๋ฅผ ์ด์๊ฐ๋ ค๊ณ ๋ ธ๋ ฅ ์ค์ด๋ค
์ทจ์ค ํ๋ด ํ๋ก์ ํธํ๋ด ์ฝํ ์ค๋นํ๋ด ๋๋ฌด ์ ์ ์๊ฒ ์ด์๊ฐ์ง๋ง ์ธ์ ๊ฐ ์ด ๋ชจ๋ ๊ฒ ์ฑ๊ณต์ ๋ค๊ฐ๊ฐ ์ ์๋ ๋ฐ๊ฑฐ๋ฆ์ด ๋๊ฒ ์ง...?
'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 20. Valid Parentheses (Easy) [TypeScript] (0) | 2024.03.08 |
|---|---|
| 704. Binary Search (Easy) [TypeScript] (0) | 2024.03.08 |
| 543. Diameter of Binary Tree (Easy) [JavaScript] (1) | 2024.02.13 |
| 104. Maximum Depth of Binary Tree (Easy) [Java] (1) | 2024.02.09 |
| 226. Invert Binary Tree (Easy) [Java] (0) | 2024.02.09 |