/
tail_recursive.rs
76 lines (61 loc) · 2.42 KB
/
tail_recursive.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
use std::cmp::Ordering;
impl Solution {
fn triangular(x: i32) -> i32 {
x * (x + 1) / 2
}
fn triangular_2(x: i32, y: i32) -> i32 {
(x * (x + 1) + y * (y + 1)) / 2
}
fn going_down(first: i32, rest: &[i32], up_length: i32, down_length: i32, result: &mut i32) {
if let Some((&second, rest)) = rest.split_first() {
match second.cmp(&first) {
Ordering::Less => Self::going_down(second, rest, up_length, down_length + 1, result),
Ordering::Equal => {
*result += Self::triangular_2(up_length, down_length) + up_length.max(down_length) + 1;
Self::going_up(second, rest, 0, result);
}
Ordering::Greater => {
*result += Self::triangular_2(up_length, down_length) + up_length.max(down_length);
Self::going_up(second, rest, 1, result);
}
}
} else {
*result += Self::triangular_2(up_length, down_length) + up_length.max(down_length) + 1;
}
}
fn going_up(first: i32, rest: &[i32], up_length: i32, result: &mut i32) {
if let Some((&second, rest)) = rest.split_first() {
match second.cmp(&first) {
Ordering::Less => Self::going_down(second, rest, up_length, 1, result),
Ordering::Equal => {
*result += Self::triangular(up_length) + up_length + 1;
Self::going_up(second, rest, 0, result);
}
Ordering::Greater => Self::going_up(second, rest, up_length + 1, result),
}
} else {
*result += Self::triangular(up_length) + up_length + 1;
}
}
pub fn candy(ratings: Vec<i32>) -> i32 {
let mut result = 0;
let (&first, rest) = ratings.split_first().unwrap();
Self::going_up(first, rest, 0, &mut result);
result
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn candy(ratings: Vec<i32>) -> i32 {
Self::candy(ratings)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}