How to find the maximum length of a subarray having a sum equal to K in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn max_length_subarray_equals_to_k(arr: &[i32], k: i32) -> usize {
    let mut map = HashMap::new(); // To store cumulative sum and its index
    let mut max_length = 0;
    let mut cumulative_sum = 0;

    for (i, &num) in arr.iter().enumerate() {
        cumulative_sum += num;

        // If the cumulative sum equals K, update max_length
        if cumulative_sum == k {
            max_length = i + 1;
        }

        // If (cumulative_sum - K) exists in the map, update max_length
        if let Some(&prev_index) = map.get(&(cumulative_sum - k)) {
            max_length = max_length.max(i - prev_index);
        }

        // Store the cumulative sum in the map if not already present
        map.entry(cumulative_sum).or_insert(i);
    }

    max_length
}

fn main() {
    let arr = [1, -1, 5, -2, -3, 2, 3, 3];
    let k = 3;

    // 1, -1, 5, -2 = 3 (length 4)
    // 5, -2 = 3 (length 2)
    // -2, -3, 2, 3, 3 = 3 (length 5)

    println!("{}", max_length_subarray_equals_to_k(&arr, k));
}




/*
run:

5

*/

 



answered Sep 5, 2025 by avibootz
...