Skip to content

Commit b633a28

Browse files
committed
feat: add solutions to lc problems: No.0122
No.0122.Best Time to Buy and Sell Stock II
1 parent ddeffd7 commit b633a28

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README.md

+42
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,34 @@ function maxProfit(prices: number[]): number {
145145
}
146146
```
147147

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+
148176
### **C++**
149177

150178
贪心:
@@ -250,6 +278,20 @@ public class Solution {
250278
}
251279
```
252280

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+
253295
### **...**
254296

255297
```

solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md

+37
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,29 @@ function maxProfit(prices: number[]): number {
122122
}
123123
```
124124

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+
125148
### **C++**
126149

127150
Greedy:
@@ -227,6 +250,20 @@ public class Solution {
227250
}
228251
```
229252

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+
230267
### **...**
231268

232269
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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+
}

0 commit comments

Comments
 (0)