Skip to content

Commit 69c0737

Browse files
committed
feat(sliding-window): add 121_best_time_to_buy_and_sell_stock.rs
1 parent 84fae21 commit 69c0737

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,9 @@ so that you can use `just tf TEST` command to test.
117117
| - | - | - |
118118
| 704. Binary Search | Easy | [704_binary_search.rs](./tests/704_binary_search.rs) |
119119
| 74. Search a 2D Matrix | Medium | [74_search_a_2d_matrix.rs](./tests/74_search_a_2d_matrix.rs) |
120+
121+
### Sliding Window
122+
123+
| Problem | Difficulty | Solution |
124+
| - | - | - |
125+
| 121. Best Time to Buy and Sell Stock | Easy | [121_best_time_to_buy_and_sell_stock.rs](./tests/121_best_time_to_buy_and_sell_stock.rs) |
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// 121. Best Time to Buy and Sell Stock
2+
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
3+
// Topics: Sliding Window.
4+
// Difficulty: Easy.
5+
6+
#[test]
7+
fn test_121_best_time_to_buy_and_sell_stock() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
impl Solution {
17+
pub fn max_profit(prices: Vec<i32>) -> i32 {
18+
let mut buy = prices[0];
19+
let mut profit = 0;
20+
for &item in prices.iter().skip(1) {
21+
if item < buy {
22+
buy = item;
23+
continue;
24+
}
25+
if item - buy > profit {
26+
profit = item - buy;
27+
}
28+
}
29+
profit
30+
}
31+
}

0 commit comments

Comments
 (0)