Skip to content

Commit 1cf6272

Browse files
committed
best time to buy and sell stock
1 parent 4c050c6 commit 1cf6272

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
/**
3+
* ์˜ค๋Š˜ ์ฃผ์‹์„ ํŒ๋งคํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด,
4+
* ์ด์ „ ๋‚ ์งœ ์ค‘ ๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€๊ฒฉ์— ๊ตฌ๋งคํ–ˆ์„ ๋•Œ ์ตœ๋Œ€ ์ด์ต์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.
5+
* ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ์ตœ์ € ๊ฐ€๊ฒฉ๊ณผ ์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์† ๊ฐฑ์‹ ํ•œ๋‹ค.
6+
*
7+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
9+
*/
10+
public int maxProfit(int[] prices) {
11+
// ํ˜„์žฌ๊นŒ์ง€ ํ™•์ธํ•œ ๋‚ ์งœ ์ค‘ ๊ฐ€์žฅ ๋‚ฎ์€ ์ฃผ๊ฐ€
12+
int minPrice = prices[0];
13+
14+
// ํ˜„์žฌ๊นŒ์ง€ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ด์ต
15+
int maxProfit = 0;
16+
17+
// ์ฒซ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ์€ minPrice๋กœ ์‚ฌ์šฉํ–ˆ์œผ๋ฏ€๋กœ ๋‘ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ๋ถ€ํ„ฐ ํ™•์ธํ•œ๋‹ค.
18+
for (int i = 1; i < prices.length; i++) {
19+
int currentPrice = prices[i];
20+
int currentProfit = currentPrice - minPrice;
21+
22+
// ์ด์ „ ์ตœ์ €๊ฐ€์— ๊ตฌ๋งคํ•˜๊ณ  ํ˜„์žฌ ๊ฐ€๊ฒฉ์— ํŒ๋งคํ–ˆ์„ ๋•Œ์˜ ์ด์ต์„ ๋น„๊ตํ•œ๋‹ค.
23+
maxProfit = Math.max(maxProfit, currentProfit);
24+
25+
// ์ดํ›„ ๋‚ ์งœ์˜ ๊ณ„์‚ฐ์„ ์œ„ํ•ด ์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ์ €๊ฐ€๋ฅผ ๊ฐฑ์‹ ํ•œ๋‹ค.
26+
minPrice = Math.min(minPrice, currentPrice);
27+
}
28+
29+
return maxProfit;
30+
}
31+
}

0 commit comments

Comments
ย (0)