How to find three consecutive numbers with the largest sum in a vector of integers in Rust

1 Answer

0 votes
// find_max_sum_of_three finds 'k' consecutive numbers with the largest sum in a slice.
// It returns an Option containing the maximum sum and a subslice of the numbers.
fn find_max_sum_of_three(numbers: &[i32], k: usize) -> Option<(i32, &[i32])> {
    // Validate input parameters: k must be greater than 0 and the slice 
    // must be at least as long as k
    if k == 0 || numbers.len() < k {
        return None;
    }

    // Compute the sum of the initial window of size k using an iterator
    let mut current_sum: i32 = numbers[..k].iter().sum();
    let mut max_sum = current_sum;
    let mut max_start_index = 0;

    // Slide the window across the remaining elements:
    // Subtract the element leaving on the left, and add the new element on the right.
    for i in k..numbers.len() {
        current_sum = current_sum - numbers[i - k] + numbers[i];

        if current_sum > max_sum {
            max_sum = current_sum;
            max_start_index = i - k + 1;
        }
    }

    // Return the max sum and the matching subslice safely
    Some((max_sum, &numbers[max_start_index..max_start_index + k]))
}

fn main() {
    let numbers = vec![4, 2, 0, 8, 7, 5, 1, 3, 9, 6];
    let k = 3;

    match find_max_sum_of_three(&numbers, k) {
        Some((sum, result)) => {
            println!("Largest sum: {}", sum);
            // Print the numbers space-separated to match the example format
            print!("Numbers: ");
            for (i, num) in result.iter().enumerate() {
                if i > 0 {
                    print!(" ");
                }
                print!("{}", num);
            }
            println!();
        }
        None => println!("Invalid parameters or slice too short."),
    }
}


/*
run:

Largest sum: 20
Numbers: 8 7 5

*/

 



answered Oct 30 by avibootz

Related questions

...