Skip to content

Commit c14f3ec

Browse files
committed
best-time-to-buy-and-sell-stock
1 parent 16977f7 commit c14f3ec

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
3+
* - ๋ฌธ์ œ ์กฐ๊ฑด 1 <= prices.length <= 10^5 ๋ฅผ ๋ณด๊ณ , ์šฐ์„  O(n^2)๋Š” ํ”ผํ•ด์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์„ ์šฐ์„ ํ•˜๊ฒŒ ๋จ.
4+
* - ๊ฒฐ๊ตญ ์ด ๋ฌธ์ œ๋Š” ๊ฐ ์ธ๋ฑ์Šค๊ฐ€ ๋‚ ์งœ ๊ฐœ๋…์œผ๋กœ ์ ์šฉ๋˜๊ธฐ ๋•Œ๋ฌธ์—, ์ˆœ์ฐจ์ ์œผ๋กœ ํ˜๋Ÿฌ๊ฐ. (์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์‚ฐํ•  ๋•Œ ๊ฒฐ๊ตญ ๊ฐ ์ผ์ž ๋ณ„๋กœ ๋‚ด๊ฐ€ ์–ผ๋งˆ์˜ ์ด๋“์„ ๋ดค๋Š”์ง€๋ฅผ ๊ณ„์‚ฐํ•˜๊ณ , ์ด ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ๊ณ ๋ฅด๋ฉด ๋˜๋Š” ๊ตฌ์กฐ)
5+
* - ๋”ฐ๋ผ์„œ ํ•œ ๋ฒˆ์˜ ์ˆœํšŒ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ์Œ
6+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
7+
*/
8+
class Solution {
9+
public int maxProfit(int[] prices) {
10+
int minPrice = prices[0];
11+
int maxProfit = 0;
12+
13+
for (int i = 1; i < prices.length; i++) {
14+
if (prices[i] < minPrice) {
15+
minPrice = prices[i];
16+
}
17+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
18+
}
19+
20+
return maxProfit;
21+
}
22+
}

0 commit comments

Comments
ย (0)