MCPcopy Create free account
hub / github.com/Ainevsia/Leetcode-Rust / candy

Method candy

135. Candy/src/main.rs:9–37  ·  view source on GitHub ↗

two pass solution with O(n) time and O(n) space

(ratings: Vec<i32>)

Source from the content-addressed store, hash-verified

7impl Solution {
8 /// two pass solution with O(n) time and O(n) space
9 pub fn candy(ratings: Vec<i32>) -> i32 {
10 if ratings.len() <= 1 { return ratings.len() as i32 }
11 let mut total = 1;
12 let mut prev = 1;
13 let mut count_down = 0;
14 for i in 1..ratings.len() {
15 if ratings[i] >= ratings[i-1] {
16 if count_down > 0 {
17 total += count_down * (count_down + 1) / 2;
18 if count_down >= prev {
19 total += count_down - prev + 1;
20 }
21 count_down = 0;
22 prev = 1;
23 }
24 prev = if ratings[i] == ratings[i-1] { 1 } else { prev + 1 };
25 total += prev;
26 } else {
27 count_down += 1;
28 }
29 }
30 if count_down > 0 {
31 total += count_down * (count_down + 1) / 2;
32 if count_down >= prev {
33 total += count_down - prev + 1;
34 }
35 }
36 total as i32
37 }
38}
39
40#[cfg(test)]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected