-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
55 lines (50 loc) · 1.44 KB
/
main.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
fn main() {
assert_eq!(Solution::candy(vec![1,0,2]), 5);
}
struct Solution {}
impl Solution {
/// two pass solution with O(n) time and O(n) space
pub fn candy(ratings: Vec<i32>) -> i32 {
if ratings.len() <= 1 { return ratings.len() as i32 }
let mut total = 1;
let mut prev = 1;
let mut count_down = 0;
for i in 1..ratings.len() {
if ratings[i] >= ratings[i-1] {
if count_down > 0 {
total += count_down * (count_down + 1) / 2;
if count_down >= prev {
total += count_down - prev + 1;
}
count_down = 0;
prev = 1;
}
prev = if ratings[i] == ratings[i-1] { 1 } else { prev + 1 };
total += prev;
} else {
count_down += 1;
}
}
if count_down > 0 {
total += count_down * (count_down + 1) / 2;
if count_down >= prev {
total += count_down - prev + 1;
}
}
total as i32
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::candy(vec![1,0,2]), 5);
assert_eq!(Solution::candy(vec![1,2,2]), 4);
assert_eq!(Solution::candy(vec![1,3,2,2,1]), 7);
}
#[test]
fn fail() {
assert_eq!(Solution::candy(vec![1,2,3,1,0]), 9);
}
}