Created
May 27, 2015 02:22
-
-
Save ferristseng/b533e52c4c5b98377e34 to your computer and use it in GitHub Desktop.
Largest contiguous sum practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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