Skip to content

Commit 8ebb550

Browse files
committed
Rust: 1D_dynamic_array, 3 solutions
1 parent 0e2e3dc commit 8ebb550

File tree

4 files changed

+55
-4
lines changed

4 files changed

+55
-4
lines changed

rust/03_sliding_window/121_best_time_to_buy.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use super::std::cmp;
1+
use std::cmp;
2+
23
impl Solution {
34
pub fn max_profit(prices: Vec<i32>) -> i32 {
45
let mut l = 0;
@@ -7,11 +8,11 @@ impl Solution {
78
while r < prices.len() {
89
if prices[l] < prices[r] {
910
let profit = prices[r] - prices[l];
10-
max_profit = cmp::max(profit, max_profit)
11+
max_profit = cmp::max(profit, max_profit);
1112
} else {
12-
l = r
13+
l = r;
1314
}
14-
r += 1
15+
r += 1;
1516
}
1617
max_profit
1718
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// time complexity: O(n)
2+
// space complexity: O(1)
3+
4+
impl Solution {
5+
pub fn rob(mut nums: Vec<i32>) -> i32 {
6+
if nums.len() == 1{
7+
return nums[0];
8+
}
9+
10+
nums[1] = nums[0].max(nums[1]);
11+
12+
for i in 2..nums.len(){
13+
nums[i] = nums[i-1].max(nums[i - 2] + nums[i]);
14+
}
15+
16+
*nums.last().unwrap()
17+
}
18+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
impl Solution {
3+
pub fn climb_stairs(n: i32) -> i32 {
4+
if n == 1{
5+
return 1;
6+
}
7+
8+
let (mut one, mut two) = (1, 2);
9+
10+
for i in 2..n{
11+
let tmp = two;
12+
two = two + one;
13+
one = tmp;
14+
}
15+
16+
two
17+
}
18+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// time compexity : O(n)
2+
// space compexity : O(1)
3+
4+
impl Solution {
5+
pub fn min_cost_climbing_stairs(mut cost: Vec<i32>) -> i32 {
6+
for i in 2..cost.len(){
7+
cost[i] += cost[i- 1].min(cost[i-2]);
8+
}
9+
10+
let len = cost.len();
11+
12+
cost[len - 1].min(cost[len - 2])
13+
}
14+
}

0 commit comments

Comments
 (0)