![]() |
VOOZH | about |
Given an array arr[] of size n containing integers, the task is to find the length of the longest subarray having sum equal to the given value k.
Note: If there is no subarray with sum equal to k, return 0.
Examples:
Input: arr[] = [10, 5, 2, 7, 1, -10], k = 15
Output: 6
Explanation: Subarrays with sum = 15 are [5, 2, 7, 1], [10, 5] and [10, 5, 2, 7, 1, -10]. The length of the longest subarray with a sum of 15 is 6.Input: arr[] = [-5, 8, -14, 2, 4, 12], k = -5
Output: 5
Explanation: Only subarray with sum = 15 is [-5, 8, -14, 2, 4] of length 5.Input: arr[] = [10, -10, 20, 30], k = 5
Output: 0
Explanation: No subarray with sum = 5 is present in arr[].
Table of Content
The idea is to check the sum of all the subarrays and return the length of the longest subarray having the sumk.
6
If you take a closer look at this problem, this is mainly an extension of Longest Subarray with 0 sum.
The idea is based on the fact that if Sj - Si = k (where Si and Sj are prefix sums till index i and j respectively, and i < j), then the subarray between i+1 to j has sum equal to k.
For example, arr[] = [5, 2, -3, 4, 7] and k = 3. The value of S3 - S0= 3, it means the subarray from index 1 to 3 has sum equals to 3.So we mainly compute prefix sums in the array and store these prefix sums in a hash table. And check if currentprefix sum - k is already present. If currentprefix sum - k is present in the hash table and is mapped to index j, then subarray from j to current index has sum equal to k.
Below are the main points to consider in your implementation.
6
Related Problem