


Input: ‘n’ = 7 ‘k’ = 3
‘a’ = [1, 2, 3, 1, 1, 1, 1]
Output: 3
Explanation: Subarrays whose sum = ‘3’ are:
[1, 2], [3], [1, 1, 1] and [1, 1, 1]
Here, the length of the longest subarray is 3, which is our final answer.
The first line contains two integers, ‘n’ and ‘k’, denoting the size of array ‘a’ and the integer ‘k’.
The following line contains ‘n’ integers, denoting the array ‘a’.
Print the length of the longest subarray whose sum is equal to ‘k’.
You do not need to print anything; it has already been taken care of. Just implement the given function.
Use two nested loops to generate all subarrays. The first loop will decide the starting index of the subarray. The second loop will start from the starting index and generate all possible subarrays from the ‘starting index’.
At each point, check whether the sum of the current subarray is equal to the required sum.
If the current sum = ‘k’, check whether the length of the current subarray is greater than the maximum value we have found. If this is true, the length of the current subarray is now the maximum length (we have found so far). Else, we continue.
function longestSubarrayWithSumK(int[] a, int n, int k):
We will use two indices: ‘startIndex’ and ‘endIndex’. This algorithm works as follows: We first fix the startIndex and will increase the endIndex (which increases the size of our current subarray). We do this till our sum <= ‘k’, or we are not out of bounds. Now we check our current sum and compare it with ‘k’.
Now we may encounter these cases:
This will be when our endIndex has reached the end of the array. Now, we can stop our program and return the maximum answer we have found.
We have found a subarray with the required sum. We will now compare the length of the current subarray with the maximum we have found so far and replace it with the greatest.
We now shift the startIndex (increasing it by one and hence decreasing the size of our window) but subtract the current starting element before increasing.
We will increase the startIndex till it is < n, after which we will return our maximum answer,
// Function to find the longest subarray with sum ‘k’
function longestSubarrayWithSumK(int[] a, int n, int k):