problems(rs): add “303. Range Sum Query - Immutable”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-04-16 00:05:53 +02:00
parent 09a14a0e3d
commit 43d043b5e1
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,45 @@
#[derive(Debug)]
struct NumArray {
prefix_sums: Vec<i32>,
}
impl NumArray {
fn new(nums: Vec<i32>) -> Self {
let mut total = nums.iter().sum::<i32>();
let mut prefix_sums: Vec<i32> = 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);
}
}