Given: Unsorted array
Find: Subarray starting index to last index on summing up gives the given sum
arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
C++ Solution
#include <iostream>
#include <cstdio>
using namespace std;
int subwithsum(int arr[],int n, int sum)
{
int curr_sum, i, j;
for (int i=0; i<n; i++)
{
curr_sum=arr[i];
for (j=i+1; j<=n; j++)
{
if(curr_sum==sum)
{
cout<<i<<"and"<<j-1;
return 1;
}
if(curr_sum>sum || j==n)
break;
curr_sum=curr_sum + arr[j];
}
}
cout<<"no sub array";
return 0;
}
int main()
{
int arr[]={3,8,2,1,9};
int n=5,sum=10;
subwithsum(arr,n,sum);
return 0;
}
No comments:
Post a Comment