Skip to content

Commit d9fa9da

Browse files
committed
greedy
1 parent c7d2f5c commit d9fa9da

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ mod prob_125;
8080
mod prob_127;
8181
mod prob_131;
8282
mod prob_132;
83+
mod prob_134;
84+
mod prob_135;
8385
mod prob_144;
8486
mod prob_149;
8587
mod prob_159;

src/prob_134.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
impl Solution {
3+
pub fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
4+
if gas.iter().sum::<i32>() < cost.iter().sum() {
5+
return -1;
6+
}
7+
let mut ans = -1;
8+
let mut rest = 0;
9+
let mut i = 0;
10+
while i < gas.len() {
11+
if ans == -1 && gas[i]<cost[i] {
12+
i+=1;
13+
continue;
14+
}
15+
if ans == -1 {
16+
rest = gas[i] - cost[i];
17+
ans = i as i32;
18+
i+=1;
19+
} else {
20+
rest += gas[i] - cost[i];
21+
if rest < 0 {
22+
ans = -1;
23+
} else {
24+
i+=1;
25+
}
26+
}
27+
}
28+
ans
29+
}
30+
}
31+
32+
struct Solution;
33+
34+
#[cfg(test)]
35+
mod tests {
36+
use super::Solution;
37+
38+
#[test]
39+
fn test_can_complete_circuit() {
40+
let test_cases = vec![
41+
(vec![1,2,3,4,5], vec![3,4,5,1,2], 3),
42+
(vec![2,3,4], vec![3,4,3], -1),
43+
];
44+
for (gas, cost, expect) in test_cases {
45+
assert_eq!(Solution::can_complete_circuit(gas.clone(), cost.clone()), expect, "gas: {:?}, cost: {:?}", gas, cost);
46+
}
47+
}
48+
}

src/prob_135.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
impl Solution {
2+
pub fn candy(ratings: Vec<i32>) -> i32 {
3+
let n = ratings.len();
4+
if n < 2 {
5+
return n as i32;
6+
}
7+
let mut v = vec![1; n];
8+
9+
for i in 1..n {
10+
if ratings[i] > ratings[i-1] {v[i] = v[i-1]+1;}
11+
}
12+
for i in (0..n-1).rev() {
13+
if ratings[i] > ratings[i+1] {v[i] = v[i].max(v[i+1]+1);}
14+
}
15+
v.iter().sum()
16+
}
17+
}
18+
19+
struct Solution;
20+
21+
#[cfg(test)]
22+
mod tests {
23+
use super::Solution;
24+
25+
#[test]
26+
fn test_candy() {
27+
let test_cases = vec![
28+
(vec![1,0,2],5),
29+
(vec![1,2,3,4,4,3,2,1], 20),
30+
(vec![1,2,3,4,3,2,1], 16),
31+
(vec![5,4,3,2,1], 15),
32+
(vec![5,5,5,5,5], 5),
33+
(vec![5,4,4,3,3,3], 8),
34+
(vec![5,4,4,3,3,8], 9),
35+
(vec![5,4,4,3,3,2], 9),
36+
(vec![1,2,2],4),
37+
];
38+
for (ratings, expect) in test_cases {
39+
assert_eq!(Solution::candy(ratings.clone()), expect, "ratings: {:?}", ratings);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)