function maxLengthSubarrayEqualsToK(arr, K) {
let map = new Map(); // To store cumulative sum and its index
let maxLength = 0;
let cumulativeSum = 0;
const size = arr.length;
for (let i = 0; i < size; i++) {
cumulativeSum += arr[i];
// If the cumulative sum equals K, update maxLength
if (cumulativeSum === K) {
maxLength = i + 1;
}
// If (cumulativeSum - K) exists in the map, update maxLength
if (map.has(cumulativeSum - K)) {
maxLength = Math.max(maxLength, i - map.get(cumulativeSum - K));
}
// Store the cumulative sum in the map if not already present
if (!map.has(cumulativeSum)) {
map.set(cumulativeSum, i);
}
}
return maxLength;
}
const arr = [1, -1, 5, -2, -3, 2, 3, 3];
let K = 3;
// 1, -1, 5, -2 = 3 (4)
// 5, -2 = 3 (2)
// -2, -3, 2, 3, 3 = 3 (5)
console.log(maxLengthSubarrayEqualsToK(arr, K));
/*
run:
5
*/