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

1 Answer

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

 

 



answered Feb 24, 2024 by avibootz
edited Sep 5, 2025 by avibootz
...