1def smallestSubWithSum(arr, n, x):
2
3 # Initialize current sum and minimum length
4 curr_sum = 0
5 min_len = n + 1
6
7 # Initialize starting and ending indexes
8 start = 0
9 end = 0
10 while (end < n):
11
12 # Keep adding array elements while current
13 # sum is smaller than or equal to x
14 while (curr_sum <= x and end < n):
15 curr_sum += arr[end]
16 end += 1
17
18 # If current sum becomes greater than x.
19 while (curr_sum > x and start < n):
20
21 # Update minimum length if needed
22 if (end - start < min_len):
23 min_len = end - start
24
25 # remove starting elements
26 curr_sum -= arr[start]
27 start += 1
28
29 return min_len
1def max_length(s, k):
2 current = []
3 max_len = -1 # returns -1 if there is no subsequence that adds up to k.
4 for i in s:
5 current.append(i)
6 while sum(current) > k: # Shrink the array from the left, until the sum is <= k.
7 current = current[1:]
8 if sum(current) == k:
9 max_len = max(max_len, len(current))
10
11 return max_len
1//variable size sliding window
2#include <bits/stdc++.h>
3
4using namespace std;
5
6int main()
7{
8 int n;
9 cout<<"Enter the size of the array:"<<endl;
10 cin>>n;
11 int arr[n];
12 cout<<"Enter the elements of the array:"<<endl;
13 for(int i=0;i<n;i++)
14 {
15 cin>>arr[i];
16 }
17 int k;
18 cout<<"enter the sum whose longest subarray you want to find:"<<endl;
19 cin>>k;
20 int i=0,j=0,sum=0;
21 int mx=0;
22 while(j<n)
23 {
24 sum=sum+arr[j];
25 if(sum<k)
26 {
27 j++;
28 }
29 else if(sum==k)
30 {
31 mx=max(mx,j-i+1);
32 j++;
33 }
34 else
35 {
36 while(sum>k)
37 {
38 sum=sum-arr[i];
39 i++;
40 }
41 j++;
42 }
43 }
44 cout<<mx<<endl;
45 return 0;
46}
47