File tree Expand file tree Collapse file tree 3 files changed +49
-0
lines changed
solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -98,6 +98,24 @@ class Solution {
98
98
}
99
99
```
100
100
101
+ ### ** TypeScript**
102
+
103
+ ```
104
+ function maxProfit(prices: number[]): number {
105
+ const n = prices.length;
106
+ let dp = Array.from({ length: n }, v => new Array(3).fill(0));
107
+ dp[0] = [0, -prices[0], Number.MIN_SAFE_INTEGER];
108
+ for (let i = 1; i < n; i++) {
109
+ dp[i] = [
110
+ Math.max(dp[i - 1][0], dp[i - 1][2]),
111
+ Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]),
112
+ dp[i - 1][1] + prices[i]
113
+ ];
114
+ }
115
+ return Math.max(dp[n - 1][0], dp[n - 1][2]);
116
+ };
117
+ ```
118
+
101
119
### ** C++**
102
120
103
121
``` cpp
Original file line number Diff line number Diff line change @@ -73,6 +73,24 @@ class Solution {
73
73
}
74
74
```
75
75
76
+ ### ** TypeScript**
77
+
78
+ ```
79
+ function maxProfit(prices: number[]): number {
80
+ const n = prices.length;
81
+ let dp = Array.from({ length: n }, v => new Array(3).fill(0));
82
+ dp[0] = [0, -prices[0], Number.MIN_SAFE_INTEGER];
83
+ for (let i = 1; i < n; i++) {
84
+ dp[i] = [
85
+ Math.max(dp[i - 1][0], dp[i - 1][2]),
86
+ Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]),
87
+ dp[i - 1][1] + prices[i]
88
+ ];
89
+ }
90
+ return Math.max(dp[n - 1][0], dp[n - 1][2]);
91
+ };
92
+ ```
93
+
76
94
### ** C++**
77
95
78
96
``` cpp
Original file line number Diff line number Diff line change
1
+ function maxProfit ( prices : number [ ] ) : number {
2
+ const n = prices . length ;
3
+ let dp = Array . from ( { length : n } , v => new Array ( 3 ) . fill ( 0 ) ) ;
4
+ dp [ 0 ] = [ 0 , - prices [ 0 ] , Number . MIN_SAFE_INTEGER ] ;
5
+ for ( let i = 1 ; i < n ; i ++ ) {
6
+ dp [ i ] = [
7
+ Math . max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 2 ] ) ,
8
+ Math . max ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] - prices [ i ] ) ,
9
+ dp [ i - 1 ] [ 1 ] + prices [ i ]
10
+ ] ;
11
+ }
12
+ return Math . max ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 2 ] ) ;
13
+ } ;
You can’t perform that action at this time.
0 commit comments