Skip to content

Commit 1aabf5b

Browse files
authored
Merge pull request #2509 from dohyeon2/week5
2 parents 0add5a1 + 3f7066f commit 1aabf5b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
// TC : O(n)
3+
// SC : O(1)
4+
public int maxProfit(int[] prices) {
5+
int maximumProfit = 0;
6+
int cursor = 0;
7+
8+
// ์ „์ฒด๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์ด์ต์„ ๊ฒ€์ฆ
9+
for(int i = 0; i < prices.length; i++){
10+
int profit = prices[i] - prices[cursor];
11+
12+
// ๋งŒ์•ฝ ํ˜„์žฌ ๊ฐ’์ด ์ปค์„œ์˜ ๊ฐ’๋ณด๋‹ค ๋” ์ž‘๋‹ค๋ฉด ํ˜„์žฌ ๊ฐ’๋ถ€ํ„ฐ ๋น„๊ตํ•˜๊ธฐ ์‹œ์ž‘
13+
if(profit < 0){
14+
cursor = i;
15+
continue;
16+
}
17+
18+
// ์ด์ „์— ์ปค์„œ๋กœ ์ถ”์ •ํ•œ ๊ฐ’์ด ๋†’๋”๋ผ๋„ Math.max๋กœ ๋ณด์กด๋จ
19+
maximumProfit = Math.max(profit, maximumProfit);
20+
}
21+
22+
return maximumProfit;
23+
}
24+
}

0 commit comments

Comments
ย (0)