Skip to content

Commit f8aa2fc

Browse files
best test to by and sell stock solution
1 parent 232f11a commit f8aa2fc

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class SolutionJaeJeong {
2+
3+
public int maxProfit(int[] prices) {
4+
// ์ฃผ์–ด์ง„ ๊ฐ€๊ฒฉ ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง€๊ณ  prices[i]๋Š” i๋ฒˆ์งธ ๋‚ ์˜ ์ฃผ์–ด์ง„ ์ฃผ์‹ ๊ฐ€๊ฒฉ
5+
// ํ•œ ์ฃผ์‹์„ ๋งค์ˆ˜ํ•  ๋‹จ์ผ ๋‚ ์งœ๋ฅผ ์„ ํƒํ•˜๊ณ , ๋งค๋„ํ•  ๋ฏธ๋ž˜์˜ ๋‹ค๋ฅธ ๋‚ ์งœ๋ฅผ ์„ ํƒํ•ด ์ˆ˜์ต์„ ๊ทน๋Œ€ํ™”
6+
// ์ด ๊ฑฐ๋ž˜์—์„œ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ˆ˜์ต์„ ๋ฐ˜ํ™˜ํ•ด๋ผ, ์ˆ˜์ต์„ ์–ป์„ ์ˆ˜ ์—†์œผ๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•ด๋ผ
7+
// ์‹ธ๊ฒŒ ๋งค์ˆ˜ํ•ด์„œ ๋น„์‹ธ๊ฒŒ ๋งค๋„ํ•ด๋ผ
8+
9+
// 3๋ฒˆ์งธ ํ’€์ด
10+
// ์ตœ๋Œ€ ์ด์ต: ํ˜„์žฌ ๊ฐ€๊ฒฉ - ์ด์ „ ๊ฐ€๊ฒฉ ์ค‘ ์ตœ์ € ๊ฐ€๊ฒฉ
11+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(N), ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
12+
int minPrice = prices[0];
13+
int maxProfit = 0;
14+
for (int i = 1; i < prices.length; i++) {
15+
if (prices[i - 1] < minPrice) {
16+
minPrice = prices[i - 1];
17+
}
18+
19+
var profit = prices[i] - minPrice;
20+
if (profit > maxProfit) {
21+
maxProfit = profit;
22+
}
23+
}
24+
25+
return maxProfit;
26+
}
27+
}

0 commit comments

Comments
ย (0)