Skip to content

Commit 16f9130

Browse files
committed
add besttime to buy and sell stock solution
1 parent 2af5961 commit 16f9130

File tree

1 file changed

+33
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)