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
*/