Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Maximum Subarray Implementation #777

Merged
merged 3 commits into from
Aug 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 66 additions & 46 deletions src/dynamic_programming/maximum_subarray.rs
Original file line number Diff line number Diff line change
@@ -1,62 +1,82 @@
/// ## maximum subarray via Dynamic Programming
//! This module provides a function to find the the largest sum of the subarray
//! in a given array of integers using dynamic programming. It also includes
//! tests to verify the correctness of the implementation.

/// maximum_subarray(array) find the subarray (containing at least one number) which has the largest sum
/// and return its sum.
/// Custom error type for maximum subarray
#[derive(Debug, PartialEq)]
pub enum MaximumSubarrayError {
EmptyArray,
}

/// Finds the subarray (containing at least one number) which has the largest sum
/// and returns its sum.
///
/// A subarray is a contiguous part of an array.
///
/// Arguments:
/// * `array` - an integer array
/// Complexity
/// - time complexity: O(array.length),
/// - space complexity: O(array.length),
pub fn maximum_subarray(array: &[i32]) -> i32 {
let mut dp = vec![0; array.len()];
dp[0] = array[0];
let mut result = dp[0];

for i in 1..array.len() {
if dp[i - 1] > 0 {
dp[i] = dp[i - 1] + array[i];
} else {
dp[i] = array[i];
}
result = result.max(dp[i]);
/// # Arguments
///
/// * `array` - A slice of integers.
///
/// # Returns
///
/// A `Result` which is:
/// * `Ok(isize)` representing the largest sum of a contiguous subarray.
/// * `Err(MaximumSubarrayError)` if the array is empty.
///
/// # Complexity
///
/// * Time complexity: `O(array.len())`
/// * Space complexity: `O(1)`
pub fn maximum_subarray(array: &[isize]) -> Result<isize, MaximumSubarrayError> {
if array.is_empty() {
return Err(MaximumSubarrayError::EmptyArray);
}

result
let mut cur_sum = array[0];
let mut max_sum = cur_sum;

for &x in &array[1..] {
cur_sum = (cur_sum + x).max(x);
max_sum = max_sum.max(cur_sum);
}

Ok(max_sum)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn non_negative() {
//the maximum value: 1 + 0 + 5 + 8 = 14
let array = vec![1, 0, 5, 8];
assert_eq!(maximum_subarray(&array), 14);
}

#[test]
fn negative() {
//the maximum value: -1
let array = vec![-3, -1, -8, -2];
assert_eq!(maximum_subarray(&array), -1);
}

#[test]
fn normal() {
//the maximum value: 3 + (-2) + 5 = 6
let array = vec![-4, 3, -2, 5, -8];
assert_eq!(maximum_subarray(&array), 6);
macro_rules! maximum_subarray_tests {
($($name:ident: $tc:expr,)*) => {
$(
#[test]
fn $name() {
let (array, expected) = $tc;
assert_eq!(maximum_subarray(&array), expected);
}
)*
}
}

#[test]
fn single_element() {
let array = vec![6];
assert_eq!(maximum_subarray(&array), 6);
let array = vec![-6];
assert_eq!(maximum_subarray(&array), -6);
maximum_subarray_tests! {
test_all_non_negative: (vec![1, 0, 5, 8], Ok(14)),
test_all_negative: (vec![-3, -1, -8, -2], Ok(-1)),
test_mixed_negative_and_positive: (vec![-4, 3, -2, 5, -8], Ok(6)),
test_single_element_positive: (vec![6], Ok(6)),
test_single_element_negative: (vec![-6], Ok(-6)),
test_mixed_elements: (vec![-2, 1, -3, 4, -1, 2, 1, -5, 4], Ok(6)),
test_empty_array: (vec![], Err(MaximumSubarrayError::EmptyArray)),
test_all_zeroes: (vec![0, 0, 0, 0], Ok(0)),
test_single_zero: (vec![0], Ok(0)),
test_alternating_signs: (vec![3, -2, 5, -1], Ok(6)),
test_all_negatives_with_one_positive: (vec![-3, -4, 1, -7, -2], Ok(1)),
test_all_positives_with_one_negative: (vec![3, 4, -1, 7, 2], Ok(15)),
test_all_positives: (vec![2, 3, 1, 5], Ok(11)),
test_large_values: (vec![1000, -500, 1000, -500, 1000], Ok(2000)),
test_large_array: ((0..1000).collect::<Vec<_>>(), Ok(499500)),
test_large_negative_array: ((0..1000).map(|x| -x).collect::<Vec<_>>(), Ok(0)),
test_single_large_positive: (vec![1000000], Ok(1000000)),
test_single_large_negative: (vec![-1000000], Ok(-1000000)),
}
}