Skip to content

Commit 66ceabd

Browse files
donghyeon95donghyeon95
authored andcommitted
feat: Best Time to Buy And Sell Stock #221
1 parent c48048d commit 66ceabd

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
int result = 0;
4+
int maxProfit = 0;
5+
int buyStock = prices[0];
6+
7+
// ํ•œ๋ฒˆ ๋Œ๋ฉด์„œ ๋‚˜๋ณด๋‹ค ์ž‘์€ ๊ฒƒ์ด ๋‚˜์˜ฌ ๋•Œ๊นŒ์ง€ ์ด์ต์„ ๋ณธ๋‹ค
8+
9+
10+
for (int price: prices) {
11+
// ๋‚˜๋ณด๋‹ค ์ž‘์€ ๊ฒŒ ๋‚˜์˜ค๋ฉด MAX ์ด์ต์„ ๊ฐฑ์‹ ํ•˜๊ณ  ๊ฑฐ๊ธฐ๋ถ€์„œ ๋‹ค์‹œ ์‹œ์ž‘ํ•œ๋‹ค.
12+
if (price < buyStock) {
13+
result = Math.max(result, maxProfit);
14+
maxProfit = 0;
15+
buyStock = price;
16+
} else {
17+
maxProfit = Math.max(price - buyStock, maxProfit);
18+
}
19+
}
20+
21+
return Math.max(result, maxProfit);
22+
}
23+
}

0 commit comments

Comments
ย (0)