From d3c127480bb1b9d84245f5162d427d4a6c8d5d33 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 1 Feb 2024 11:13:56 +0800 Subject: [PATCH] 20240201 Finished --- src/problem/lcp24_nums_game.rs | 65 ++++++++++++++++++++++++++++++++++ src/problem/mod.rs | 3 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 src/problem/lcp24_nums_game.rs diff --git a/src/problem/lcp24_nums_game.rs b/src/problem/lcp24_nums_game.rs new file mode 100644 index 0000000..df915c8 --- /dev/null +++ b/src/problem/lcp24_nums_game.rs @@ -0,0 +1,65 @@ +pub struct Solution {} + +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn nums_game(nums: Vec) -> Vec { + let mut result = Vec::with_capacity(nums.len()); + let m = 1000000007i64; + + let (mut lower, mut upper) = + (BinaryHeap::new(), BinaryHeap::new()); + let (mut lower_sum, mut upper_sum) = (0i64, 0i64); + + for (index, value) in nums.iter().enumerate() { + let value = *value - index as i32; + + let peek = lower.peek(); + if peek.is_none() || *peek.unwrap() >= value { + lower_sum += value as i64; + lower.push(value); + + if lower.len() > upper.len() + 1 { + let peek = lower.pop().unwrap(); + + upper.push(Reverse(peek)); + upper_sum += peek as i64; + lower_sum -= peek as i64; + } + } else { + upper_sum += value as i64; + upper.push(Reverse(value)); + + if lower.len() < upper.len() { + let peek = upper.pop().unwrap().0; + + lower.push(peek); + lower_sum += peek as i64; + upper_sum -= peek as i64; + } + } + + if (index + 1) % 2 == 0 { + result.push(((upper_sum - lower_sum) % m) as i32 ); + } else { + result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) + % m) as i32); + } + } + + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_lcp24() { + assert_eq!(Solution::nums_game(vec![3,4,5,1,6,7]), vec![0,0,0,5,6,7]); + assert_eq!(Solution::nums_game(vec![1,2,3,4,5]), vec![0,0,0,0,0]); + assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154,375]); + } +} diff --git a/src/problem/mod.rs b/src/problem/mod.rs index b7c376d..827b093 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -33,4 +33,5 @@ mod p2861_maximum_number_of_alloys; mod p365_water_and_jug_problem; mod p514_freedom_trail; mod p2808_minimum_seconds_to_equalize_a_circular_array; -mod p2670_find_the_distinct_difference_array; \ No newline at end of file +mod p2670_find_the_distinct_difference_array; +mod lcp24_nums_game; \ No newline at end of file