File tree 3 files changed +88
-0
lines changed
solution/0100-0199/0122.Best Time to Buy and Sell Stock II
3 files changed +88
-0
lines changed Original file line number Diff line number Diff line change @@ -145,6 +145,34 @@ function maxProfit(prices: number[]): number {
145
145
}
146
146
```
147
147
148
+ 拆解分析:
149
+
150
+ ``` ts
151
+ function maxProfit(prices : number []): number {
152
+ const n = prices .length ;
153
+ let res = 0 ;
154
+ let max = prices [0 ];
155
+ let min = prices [0 ];
156
+ for (let i = 1 ; i < n ; i ++ ) {
157
+ const price = prices [i ];
158
+ // 如果今天的价格比最高点要低,则交易之前的最大差值,再买入今天的
159
+ if (price < max ) {
160
+ res += max - min ;
161
+ max = price ;
162
+ min = price ;
163
+ } else {
164
+ // 非小于,更新最高点
165
+ max = price ;
166
+ }
167
+ }
168
+ // 防止漏算最后一笔交易
169
+ if (min < max ) {
170
+ res += max - min ;
171
+ }
172
+ return res ;
173
+ }
174
+ ```
175
+
148
176
### ** C++**
149
177
150
178
贪心:
@@ -250,6 +278,20 @@ public class Solution {
250
278
}
251
279
```
252
280
281
+ ### ** Rust**
282
+
283
+ ``` rust
284
+ impl Solution {
285
+ pub fn max_profit (prices : Vec <i32 >) -> i32 {
286
+ let mut res = 0 ;
287
+ for i in 1 .. prices . len () {
288
+ res += 0. max (prices [i ] - prices [i - 1 ]);
289
+ }
290
+ res
291
+ }
292
+ }
293
+ ```
294
+
253
295
### ** ...**
254
296
255
297
```
Original file line number Diff line number Diff line change @@ -122,6 +122,29 @@ function maxProfit(prices: number[]): number {
122
122
}
123
123
```
124
124
125
+ ``` ts
126
+ function maxProfit(prices : number []): number {
127
+ const n = prices .length ;
128
+ let res = 0 ;
129
+ let max = prices [0 ];
130
+ let min = prices [0 ];
131
+ for (let i = 1 ; i < n ; i ++ ) {
132
+ const price = prices [i ];
133
+ if (price < max ) {
134
+ res += max - min ;
135
+ max = price ;
136
+ min = price ;
137
+ } else {
138
+ max = price ;
139
+ }
140
+ }
141
+ if (min < max ) {
142
+ res += max - min ;
143
+ }
144
+ return res ;
145
+ }
146
+ ```
147
+
125
148
### ** C++**
126
149
127
150
Greedy:
@@ -227,6 +250,20 @@ public class Solution {
227
250
}
228
251
```
229
252
253
+ ### ** Rust**
254
+
255
+ ``` rust
256
+ impl Solution {
257
+ pub fn max_profit (prices : Vec <i32 >) -> i32 {
258
+ let mut res = 0 ;
259
+ for i in 1 .. prices . len () {
260
+ res += 0. max (prices [i ] - prices [i - 1 ]);
261
+ }
262
+ res
263
+ }
264
+ }
265
+ ```
266
+
230
267
### ** ...**
231
268
232
269
```
Original file line number Diff line number Diff line change
1
+ impl Solution {
2
+ pub fn max_profit ( prices : Vec < i32 > ) -> i32 {
3
+ let mut res = 0 ;
4
+ for i in 1 ..prices. len ( ) {
5
+ res += 0 . max ( prices[ i] - prices[ i - 1 ] ) ;
6
+ }
7
+ res
8
+ }
9
+ }
You can’t perform that action at this time.
0 commit comments