Skip to content

Commit 57c1e0b

Browse files
committed
Best Time to Buy And Sell Stock
1 parent 9d7c188 commit 57c1e0b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
// 1. 0๋ฒˆ์„ ์ œ์™ธํ•˜๊ณ  max ๋ฅผ ์ฐพ๊ณ 
4+
// 2. 0 ~ max ๋ฒ”์œ„์—์„œ min์„ ์ฐพ๋Š”๋‹ค => 2n
5+
// 3. max - min > 0 ์ด๋ฉด ๊ฐ’ ๋ฆฌํ„ด, max - min <=0 ์ด๋ฉด 0 ๋ฆฌํ„ด
6+
/*
7+
if (prices.length == 1) {
8+
return 0;
9+
}
10+
11+
int max = 1;
12+
for (int i = 1; i < prices.length; i++) {
13+
if (prices[max] <= prices[i]) {
14+
max = i;
15+
}
16+
}
17+
18+
int min = max - 1;
19+
for (int i = max - 1; i >= 0; i--) {
20+
if (prices[i] < prices[min]) {
21+
min = i;
22+
}
23+
}
24+
int result = prices[max] - prices[min];
25+
return result > 0 ? result : 0;
26+
*/
27+
// ์œ„ ํ’€์ด ์‹คํŒจ ์ผ€์ด์Šค : [3,3,5,0,0,3,1,4]
28+
// -> i๊ฐ€ max ์ผ ๋•Œ i ์ด์ „๊นŒ์ง€ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ตœ๋Œ€๊ฐ’ ๊ตฌํ•˜๊ธฐ => n^2
29+
// -> Time Limit Exceeded ๋ฐœ์ƒ
30+
// -> i ์ด์ „๊นŒ์ง€ ๋ฒ”์œ„์—์„œ ์ตœ์†Œ๊ฐ’์„ ๊ตฌํ•ด์„œ ๊ฐ’์„ ๊ตฌํ• ๊นŒ?
31+
/*
32+
int result = 0;
33+
for (int i = 1; i < prices.length; i++) {
34+
for (int j = 0; j < i; j++) {
35+
int cur = prices[i] - prices[j];
36+
if (result < cur) {
37+
result = cur;
38+
}
39+
}
40+
}
41+
return result;
42+
*/
43+
// i ์ด์ „๊นŒ์ง€ ๋ฒ”์œ„์—์„œ ์ตœ์†Œ๊ฐ’์„ ๊ตฌํ•ด์„œ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค๊ธฐ
44+
int curMin = prices[0];
45+
int result = 0;
46+
for (int i = 0; i < prices.length; i++) {
47+
if (curMin > prices[i]) {
48+
curMin = prices[i];
49+
}
50+
// System.out.println(curMin);
51+
if (result < prices[i] - curMin) {
52+
result = prices[i] - curMin;
53+
}
54+
// System.out.println(">>" + result);
55+
}
56+
return result;
57+
}
58+
}

0 commit comments

Comments
ย (0)