Skip to content

Commit e3a4251

Browse files
committed
Add problem 3381: Maximum Subarray Sum With Length Divisible by K
1 parent c1786dc commit e3a4251

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2210,6 +2210,7 @@ pub mod problem_3371_identify_the_largest_outlier_in_an_array;
22102210
pub mod problem_3375_minimum_operations_to_make_array_values_equal_to_k;
22112211
pub mod problem_3376_minimum_time_to_break_locks_i;
22122212
pub mod problem_3379_transformed_array;
2213+
pub mod problem_3381_maximum_subarray_sum_with_length_divisible_by_k;
22132214

22142215
#[cfg(test)]
22152216
mod test_utilities;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod modular_arithmetic;
2+
3+
pub trait Solution {
4+
fn max_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] as &[_], 1), 3),
14+
((&[-1, -2, -3, -4, -5], 4), -10),
15+
((&[-5, 1, 2, -3, 4], 2), 4),
16+
];
17+
18+
for ((nums, k), expected) in test_cases {
19+
assert_eq!(S::max_subarray_sum(nums.to_vec(), k), expected);
20+
}
21+
}
22+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn max_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
7+
let mut buckets = vec![i64::MAX / 2; k.cast_unsigned() as _].into_boxed_slice();
8+
let mut bucket_index = 0;
9+
let mut result = i64::MIN;
10+
let mut sum = 0;
11+
12+
assert_ne!(buckets.len(), 0);
13+
14+
buckets[0] = 0;
15+
16+
for num in nums {
17+
bucket_index += 1;
18+
19+
if bucket_index >= buckets.len() {
20+
bucket_index = 0;
21+
}
22+
23+
let bucket = &mut buckets[bucket_index];
24+
25+
sum += i64::from(num);
26+
result = result.max(sum - *bucket);
27+
*bucket = (*bucket).min(sum);
28+
}
29+
30+
result
31+
}
32+
}
33+
34+
// ------------------------------------------------------ snip ------------------------------------------------------ //
35+
36+
impl super::Solution for Solution {
37+
fn max_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
38+
Self::max_subarray_sum(nums, k)
39+
}
40+
}
41+
42+
#[cfg(test)]
43+
mod tests {
44+
#[test]
45+
fn test_solution() {
46+
super::super::tests::run::<super::Solution>();
47+
}
48+
}

0 commit comments

Comments
 (0)