Skip to content

Commit db7ac9c

Browse files
committed
best time to buy and sell stock
1 parent 5f4f2e5 commit db7ac9c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
/**
3+
dp๋ฅผ ์ด์šฉํ•œ ๋ฐฉ์‹?
4+
prices์˜ ๊ธธ์ด -> N
5+
์‹œ๊ฐ„๋ณต์žก๋„ : O(N^2) -> ์‹œ๊ฐ„ ์ดˆ๊ณผ
6+
๊ณต๊ฐ„๋ณต์žก๋„ : O(N)
7+
*/
8+
class Solution2 {
9+
public int maxProfit(int[] prices) {
10+
int[] dp =new int[prices.length];
11+
for(int i = 0; i < dp.length; i++) {
12+
for(int j = 0; j < i; j++) {
13+
dp[i] = Math.max(dp[i], prices[i] - prices[j]);
14+
}
15+
}
16+
17+
return Arrays.stream(dp)
18+
.max()
19+
.getAsInt();
20+
}
21+
}
22+
23+
/**
24+
์ด์ „ ์—ฐ์‚ฐ ๊ฐ’์„ ๊ธฐ์–ตํ•  ํ•„์š” ์—†์ด ํŠน์ • ์ธ๋ฑ์Šค ์ง€์ ๊นŒ์ง€์˜ ์ตœ์†Œ ๊ฐ’๋งŒ ์•Œ๋ฉด ๋˜๋ฏ€๋กœ,
25+
26+
prices์˜ ๊ธธ์ด -> N
27+
์‹œ๊ฐ„๋ณต์žก๋„ : O(N)
28+
๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
29+
*/
30+
class Solution {
31+
public int maxProfit(int[] prices) {
32+
int min=prices[0];
33+
int profit=0;
34+
for(int i=1; i<prices.length; i++){
35+
if(prices[i] < min){
36+
min=prices[i];
37+
continue;
38+
}
39+
profit=Math.max(profit, prices[i] - min);
40+
}
41+
return profit;
42+
}
43+
}

0 commit comments

Comments
ย (0)