Skip to content

Commit 5d06533

Browse files
committed
best-time-to-by-and-sell-stock solution
1 parent 62add02 commit 5d06533

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
/**
4+
1. ํ•˜๋ฃจ์— ํŒ”์•„์„œ ๊ฐ€์žฅ ์ตœ๋Œ€ ์ด์ต์„ ๊ตฌํ•˜๋„๋กํ•˜๋Š” max price return
5+
2. ์กฐ๊ฑด
6+
- ๋ฏธ๋ž˜ ๋‹ค๋ฅธ๋‚ ์งœ์— ํŒ๋งค (์ด์ „ ๋‚ ์งœ์— ํŒ๋งค x)
7+
- choosing a single day
8+
- ๋ฐฐ์—ด ๊ธธ์ด min = 1, max = 10^5
9+
- ์›์†Œ๊ฐ’ : min = 0, max = 10^4
10+
3. ํ’€์ด
11+
- 1)brtueforce: time complexity O(n^2), space: O(1)
12+
- 2)ํ˜„์žฌ ๊ฐ’ - ์ด์ „ ๊ฐ’ ์ค‘ ๊ฐ€์žฅ ์ตœ์†Œ๊ฐ’ -> maxProfit , ์ฆ‰ min๊ฐ’์„ ๊ณ„์† ๊ธฐ์–ตํ•˜๋‹ค๊ฐ€ ํ˜„์žฌ ๊ฐ’๊ณผ์˜ ์ฐจ์ด ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๊ตฌํ•˜๋ฉด๋œ๋‹ค.
13+
- time: O(n)
14+
- space: O(1)
15+
*/
16+
17+
int maxProfit = 0;
18+
int minStock = Integer.MAX_VALUE;
19+
int n = prices.length;
20+
21+
for(int i = 0; i<n; i++) {
22+
if(prices[i] < minStock) {
23+
minStock = prices[i];
24+
}
25+
if(i > 0 && prices[i] - minStock > maxProfit) {
26+
maxProfit = Math.max(maxProfit, prices[i] - minStock);
27+
}
28+
}
29+
return maxProfit;
30+
31+
32+
// for(int i = 0; i < n; i++) {
33+
// int curStock = prices[i];
34+
// for(int j= i + 1; j < n; j++) {
35+
// if(curStock < prices[j]) {
36+
// int curProfit = prices[j] - curStock;
37+
// maxProfit = Math.max(maxProfit, curProfit);
38+
// }
39+
// }
40+
// }
41+
// return maxProfit;
42+
}
43+
}

0 commit comments

Comments
ย (0)