You are given an array 'a' of size 'n' and an integer 'k'.
Find the length of the longest subarray of 'a' whose sum is equal to 'k'.
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.
7 3
1 2 3 1 1 1 1
3
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.
4 2
1 2 1 3
1
5 2
2 2 4 1 2
1
The expected time complexity is O(n).
1 <= 'n' <= 5 * 10 ^ 6
1 <= 'k' <= 10^18
0 <= 'a[i]' <= 10 ^ 9
Time Limit: 1-second
Generate all subarrays and check their sum.
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.
The steps are as follows:-
// Function to find the longest subarray with sum ‘k’
function longestSubarrayWithSumK(int[] a, int n, int k):
O(n ^ 2), where 'n' is the size of array ‘a’.
Since we are using two nested loops here,
Hence the time complexity is O(n ^ 2).
O(1).
Since we are only using variables to store maximum and currentMaximum,
Hence the space complexity is O(1).