Skip to content

Commit

Permalink
Rust: 1D_dynamic_array, 3 solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
tomijaga committed Jul 20, 2022
1 parent 0e2e3dc commit 8ebb550
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 4 deletions.
9 changes: 5 additions & 4 deletions rust/03_sliding_window/121_best_time_to_buy.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::std::cmp;
use std::cmp;

impl Solution {
pub fn max_profit(prices: Vec<i32>) -> i32 {
let mut l = 0;
Expand All @@ -7,11 +8,11 @@ impl Solution {
while r < prices.len() {
if prices[l] < prices[r] {
let profit = prices[r] - prices[l];
max_profit = cmp::max(profit, max_profit)
max_profit = cmp::max(profit, max_profit);
} else {
l = r
l = r;
}
r += 1
r += 1;
}
max_profit
}
Expand Down
18 changes: 18 additions & 0 deletions rust/13_1D_dynamic_programming/198_house_robber.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// time complexity: O(n)
// space complexity: O(1)

impl Solution {
pub fn rob(mut nums: Vec<i32>) -> i32 {
if nums.len() == 1{
return nums[0];
}

nums[1] = nums[0].max(nums[1]);

for i in 2..nums.len(){
nums[i] = nums[i-1].max(nums[i - 2] + nums[i]);
}

*nums.last().unwrap()
}
}
18 changes: 18 additions & 0 deletions rust/13_1D_dynamic_programming/70_climbing_stairs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

impl Solution {
pub fn climb_stairs(n: i32) -> i32 {
if n == 1{
return 1;
}

let (mut one, mut two) = (1, 2);

for i in 2..n{
let tmp = two;
two = two + one;
one = tmp;
}

two
}
}
14 changes: 14 additions & 0 deletions rust/13_1D_dynamic_programming/746_min_cost_climbing_stairs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// time compexity : O(n)
// space compexity : O(1)

impl Solution {
pub fn min_cost_climbing_stairs(mut cost: Vec<i32>) -> i32 {
for i in 2..cost.len(){
cost[i] += cost[i- 1].min(cost[i-2]);
}

let len = cost.len();

cost[len - 1].min(cost[len - 2])
}
}

0 comments on commit 8ebb550

Please sign in to comment.