Skip to content

Commit b93b9e0

Browse files
committed
Add problem 3026: Maximum Good Subarray Sum
1 parent d6cc187 commit b93b9e0

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2052,6 +2052,7 @@ pub mod problem_3016_minimum_number_of_pushes_to_type_word_ii;
20522052
pub mod problem_3019_number_of_changing_keys;
20532053
pub mod problem_3021_alice_and_bob_playing_flower_game;
20542054
pub mod problem_3024_type_of_triangle;
2055+
pub mod problem_3026_maximum_good_subarray_sum;
20552056

20562057
#[cfg(test)]
20572058
mod test_utilities;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod prefix_sums;
2+
3+
pub trait Solution {
4+
fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
((&[1, 2, 3, 4, 5, 6] as &[_], 1), 11),
14+
((&[-1, 3, 2, 4, 5], 3), 11),
15+
((&[-1, -2, -3, -4], 2), -6),
16+
];
17+
18+
for ((nums, k), expected) in test_cases {
19+
assert_eq!(S::maximum_subarray_sum(nums.to_vec(), k), expected);
20+
}
21+
}
22+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::collections::HashMap;
6+
use std::collections::hash_map::Entry;
7+
8+
impl Solution {
9+
pub fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
10+
let mut num_to_prefix_sums = HashMap::<i32, i64>::new();
11+
let mut prefix_sum = 0;
12+
let mut result = i64::MIN;
13+
14+
for num in nums {
15+
match num_to_prefix_sums.entry(num) {
16+
Entry::Occupied(occupied_entry) => {
17+
let sum = occupied_entry.into_mut();
18+
19+
*sum = (*sum).min(prefix_sum);
20+
}
21+
Entry::Vacant(vacant_entry) => {
22+
vacant_entry.insert(prefix_sum);
23+
}
24+
}
25+
26+
prefix_sum += i64::from(num);
27+
28+
for key in [num - k, num + k] {
29+
if let Some(&sum) = num_to_prefix_sums.get(&key) {
30+
result = result.max(prefix_sum - sum);
31+
}
32+
}
33+
}
34+
35+
if result == i64::MIN { 0 } else { result }
36+
}
37+
}
38+
39+
// ------------------------------------------------------ snip ------------------------------------------------------ //
40+
41+
impl super::Solution for Solution {
42+
fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
43+
Self::maximum_subarray_sum(nums, k)
44+
}
45+
}
46+
47+
#[cfg(test)]
48+
mod tests {
49+
#[test]
50+
fn test_solution() {
51+
super::super::tests::run::<super::Solution>();
52+
}
53+
}

0 commit comments

Comments
 (0)