Skip to content

Commit 835ce9f

Browse files
committed
Best Time to Buy and Sell Stock
1 parent 336cce3 commit 835ce9f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Time complexity: O(n)
3+
Space complexity: O(1)
4+
5+
i <= j ์ธ ๋‘ ์ธ๋ฑ์Šค i, j์— ๋Œ€ํ•ด์„œ, prices[j] - prices[i]๋ฅผ ์ตœ๋Œ€ํ™”ํ•ด์•ผ ํ•œ๋‹ค.
6+
7+
1. i = 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ˆœํšŒํ•œ๋‹ค.
8+
2. ํ˜„์žฌ ๊ฐ’์ด max๋ณด๋‹ค ํฌ๋‹ค๋ฉด, max๋ฅผ ๊ฐฑ์‹ ํ•˜๊ณ , min๊ณผ์˜ ์ฐจ์ด๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
9+
3. ํ˜„์žฌ ๊ฐ’์ด min๋ณด๋‹ค ์ž‘๋‹ค๋ฉด, min์„ ๊ฐฑ์‹ ํ•˜๊ณ , max ์—ญ์‹œ ๊ฐ™์€ ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ ํ•œ๋‹ค. (๊ณผ๊ฑฐ๋กœ ๋Œ์•„๊ฐ€์„œ ํŒ” ์ˆ˜๋Š” ์—†์œผ๋ฏ€๋กœ)
10+
*/
11+
class Solution {
12+
public int maxProfit(int[] prices) {
13+
int min = 999999;
14+
int max = 0;
15+
int ans = 0;
16+
for (int i = 0; i < prices.length; i++) {
17+
if (prices[i] > max) {
18+
max = prices[i];
19+
if (max - min > ans) {
20+
ans = max - min;
21+
}
22+
}
23+
if (prices[i] < min) {
24+
min = max = prices[i];
25+
}
26+
}
27+
28+
return ans;
29+
}
30+
}

0 commit comments

Comments
ย (0)