Skip to content

Instantly share code, notes, and snippets.

@ferristseng
Created May 27, 2015 02:22
Show Gist options
  • Save ferristseng/b533e52c4c5b98377e34 to your computer and use it in GitHub Desktop.
Save ferristseng/b533e52c4c5b98377e34 to your computer and use it in GitHub Desktop.
Largest contiguous sum practice
#![feature(zero_one)]
use std::cmp::Ord;
use std::num::Zero;
use std::ops::{Neg, Add};
fn largest_contiguous_sum<T>(slice: &[T]) -> T
where T : Neg + Add<T, Output = T> + Zero + Ord + Copy
{
let mut maxnow = T::zero();
let mut overall = T::zero();
for x in slice.iter() {
if maxnow + *x < T::zero() {
maxnow = T::zero();
continue;
}
maxnow = maxnow + *x;
if maxnow > overall {
overall = maxnow;
}
}
overall
}
fn main() {
println!("{:?}", largest_contiguous_sum(&[1, -1, 7, -3, -5, 2, 6, 3, 5]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment