largest subarray of sum k
def smallestSubWithSum(arr, n, x):
# Initialize current sum and minimum length
curr_sum = 0
min_len = n + 1
# Initialize starting and ending indexes
start = 0
end = 0
while (end < n):
# Keep adding array elements while current
# sum is smaller than or equal to x
while (curr_sum <= x and end < n):
curr_sum += arr[end]
end += 1
# If current sum becomes greater than x.
while (curr_sum > x and start < n):
# Update minimum length if needed
if (end - start < min_len):
min_len = end - start
# remove starting elements
curr_sum -= arr[start]
start += 1
return min_len
4.25
8
def max_length(s, k):
current = []
max_len = -1 # returns -1 if there is no subsequence that adds up to k.
for i in s:
current.append(i)
while sum(current) > k: # Shrink the array from the left, until the sum is <= k.
current = current[1:]
if sum(current) == k:
max_len = max(max_len, len(current))
return max_len
Thank you!
8
0
0
10
//variable size sliding window
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter the size of the array:"<<endl;
cin>>n;
int arr[n];
cout<<"Enter the elements of the array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int k;
cout<<"enter the sum whose longest subarray you want to find:"<<endl;
cin>>k;
int i=0,j=0,sum=0;
int mx=0;
while(j<n)
{
sum=sum+arr[j];
if(sum<k)
{
j++;
}
else if(sum==k)
{
mx=max(mx,j-i+1);
j++;
}
else
{
while(sum>k)
{
sum=sum-arr[i];
i++;
}
j++;
}
}
cout<<mx<<endl;
return 0;
}
Thank you!
10
0
5
1
//variable size sliding window
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter the size of the array:"<<endl;
cin>>n;
int arr[n];
cout<<"Enter the elements of the array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int k;
cout<<"enter the sum whose longest subarray you want to find:"<<endl;
cin>>k;
int i=0,j=0,sum=0;
int mx=0;
while(j<n)
{
sum=sum+arr[j];
if(sum<k)
{
j++;
}
else if(sum==k)
{
mx=max(mx,j-i+1);
j++;
}
else
{
while(sum>k)
{
sum=sum-arr[i];
i++;
}
j++;
}
}
cout<<mx<<endl;
return 0;
}
Thank you!
1
0
Are there any code examples left?
New code examples in category C++