5)Longest Sub-Array with Sum K -(sliding window |variable size)

Given an array containing N integers and an integer K., Your task is to find the length of the longest Sub-Array with the sum of the elements equal to the given value K.

 

Example 1:
 

Input :
A[] = {10, 5, 2, 7, 1, 9}
K = 15
Output : 4
Explanation:
The sub-array is {5, 2, 7, 1}.



method:

sliding window ,works only for positive numbers.


c++ implementation:

 int lenOfLongSubarr(int a[],  int n, int k) 
{ int i=0;int j=0; int s=0;int len=0; while(j<n) { s=s+a[j]; if(s==k) { len=max(len,j-i+1); } else if(s>k) { while(s>k) { s=s-a[i]; i++; } if(s==k) { len=max(len,j-i+1); } } j++; } return len; }
Time Complexity: O(n) 
space Complexity: O(1) 



No comments

darkmode