File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * [Problem]: [121] Best Time to Buy and Sell Stock
3+ *
4+ * (https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
5+ */
6+ function maxProfit ( prices : number [ ] ) : number {
7+ //시간복잡도: O(n^2);
8+ //공간복잡도: O(1);
9+ // Time Limit Exceeded
10+ function doublyLoopFunc ( prices : number [ ] ) : number {
11+ let result = 0 ;
12+ for ( let i = 0 ; i < prices . length ; i ++ ) {
13+ for ( let j = i + 1 ; j < prices . length ; j ++ ) {
14+ let profit = prices [ j ] - prices [ i ] ;
15+ result = Math . max ( profit , result ) ;
16+ }
17+ }
18+
19+ return result ;
20+ }
21+
22+ // 시간 복잡도: O(n)
23+ // 공간 복잡도: O(1)
24+ function twoPointerFunc ( prices : number [ ] ) : number {
25+ let minPrice = prices [ 0 ] ;
26+ let maxProfit = 0 ;
27+
28+ for ( let i = 1 ; i < prices . length ; i ++ ) {
29+ if ( prices [ i ] < minPrice ) {
30+ minPrice = prices [ i ] ;
31+ } else {
32+ maxProfit = Math . max ( maxProfit , prices [ i ] - minPrice ) ;
33+ }
34+ }
35+
36+ return maxProfit ;
37+ }
38+
39+ return twoPointerFunc ( prices ) ;
40+ }
You can’t perform that action at this time.
0 commit comments