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]);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_negative() {
let array = vec![1, 0, 5, 8];
assert_eq!(maximum_subarray(&array), 14);
}
#[test]
fn negative() {
let array = vec![-3, -1, -8, -2];
assert_eq!(maximum_subarray(&array), -1);
}
#[test]
fn normal() {
let array = vec![-4, 3, -2, 5, -8];
assert_eq!(maximum_subarray(&array), 6);
}
#[test]
fn single_element() {
let array = vec![6];
assert_eq!(maximum_subarray(&array), 6);
let array = vec![-6];
assert_eq!(maximum_subarray(&array), -6);
}
}