diff --git a/problems/range-sum-query-immutable.rs b/problems/range-sum-query-immutable.rs new file mode 100644 index 0000000..1aa4dd8 --- /dev/null +++ b/problems/range-sum-query-immutable.rs @@ -0,0 +1,45 @@ +#[derive(Debug)] +struct NumArray { + prefix_sums: Vec, +} + +impl NumArray { + fn new(nums: Vec) -> Self { + let mut total = nums.iter().sum::(); + + let mut prefix_sums: Vec = nums + .iter() + .scan(total, |total, &x| { + let prev = *total; + *total -= x; + + Some(prev) + }) + .collect(); + prefix_sums.push(0); + + Self { prefix_sums } + } + + fn sum_range(&self, left: i32, right: i32) -> i32 { + self.prefix_sums[left as usize] - self.prefix_sums[right as usize + 1] + } +} + +fn main() {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + let num_arr = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); + + dbg!("{:?}", &num_arr); + + assert_eq!(num_arr.sum_range(0, 2), 1); + assert_eq!(num_arr.sum_range(2, 5), -1); + assert_eq!(num_arr.sum_range(0, 5), -3); + } +}