From dd7dbc9d53dff295ee5ddf703519523892e4d154 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 14 Jul 2024 10:54:42 +0800 Subject: [PATCH] 20240714 Finished --- src/problem/mod.rs | 3 +- .../p918_maximum_sum_circular_subarray.rs | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/problem/p918_maximum_sum_circular_subarray.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index ca68ad9..5aff6ac 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -172,4 +172,5 @@ mod p39_combination_sum; mod p22_generate_parentheses; mod p79_word_search; mod p108_convert_sorted_array_to_binary_search_tree; -mod p53_maximum_subarray; \ No newline at end of file +mod p53_maximum_subarray; +mod p918_maximum_sum_circular_subarray; \ No newline at end of file diff --git a/src/problem/p918_maximum_sum_circular_subarray.rs b/src/problem/p918_maximum_sum_circular_subarray.rs new file mode 100644 index 0000000..5c4c988 --- /dev/null +++ b/src/problem/p918_maximum_sum_circular_subarray.rs @@ -0,0 +1,46 @@ +/** + * [918] Maximum Sum Circular Subarray + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::VecDeque; + +impl Solution { + pub fn max_subarray_sum_circular(nums: Vec) -> i32 { + let n = nums.len(); + + let mut result = nums[0]; + let mut queue = VecDeque::new(); + let mut pre = nums[0]; + queue.push_back((0, pre)); + + for i in 1..(2 * n) { + while !queue.is_empty() && queue.front().unwrap().0 + n < i { + queue.pop_front(); + } + + pre += nums[i % n]; + result = result.max(pre - queue.front().unwrap().1); + + while !queue.is_empty() && queue.back().unwrap().1 >= pre { + queue.pop_back(); + } + queue.push_back((i, pre)); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_918() { + } +}