Skip to content

Commit 66df292

Browse files
committed
0121-best-time-to-buy-and-sell-stock
1 parent 4c050c6 commit 66df292

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* TC : O(n)
3+
* - ๊ฐ€๊ฒฉ ๋ฐฐ์—ด n-1 ๋งŒํผ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(n)
4+
* SC : O(1)
5+
* - ์ƒ์ˆ˜ ๊ฐœ์˜ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ O(1)
6+
*/
7+
class Solution {
8+
public int maxProfit(int[] prices) {
9+
int maxProfit = 0; // ์•ˆ์‚ฌ๋Š” ๊ฒƒ์ด ์ตœ์„ ์ธ ๊ฒฝ์šฐ
10+
int minPrice = prices[0]; // ์ฒซ๋ฒˆ์งธ ๊ฐ€๊ฒฉ์œผ๋กœ ์‚ฌ๋Š” ๊ฒฝ์šฐ
11+
12+
for(int i=1; i<prices.length; i++) { // ๋‹ค์Œ ๋‚  ๋ถ€ํ„ฐ ์ฐจ์ต์ด ์žˆ์„ ์ˆ˜ ์žˆ์Œ.
13+
minPrice = Math.min(minPrice, prices[i]); // ์ตœ์ €๊ฐ€ ๊ฐฑ์‹ 
14+
maxProfit = Math.max(prices[i] - minPrice, maxProfit); // ์ตœ์ €๊ฐ€ ๊ธฐ์ค€ ์˜ค๋Š˜ ํŒ”์•˜์„ ๋•Œ ์ด์ต ๊ฐฑ์‹ 
15+
}
16+
return maxProfit;
17+
}
18+
}

0 commit comments

Comments
ย (0)