File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You canโt perform that action at this time.
0 commit comments