/// Its Work For Positive Value
/*
if array size n = 10
array is :: 4 2 2 0 0 5 3 8 7 1
and value is :: 8
Then minimum length sub-array is : [8]
so minimum length : 1
*/
#include<bits/stdc++.h>
using namespace std;
int minimum_length(int a[], int n, int value)
{
int currentsum = 0, minlength = n+1;
int start = 0, finish = 0;
while(finish < n)
{
while(currentsum < value && finish < n)
currentsum += a[finish++];
while(currentsum > value && start < finish)
currentsum -= a[start++];
while(currentsum == value && start < n)
{
if(finish-start < minlength)
minlength = finish - start;
currentsum -= a[start++];
}
}
return minlength;
}
int main()
{
int n, value;
cout << "Enter Array Size :: ";
cin >> n;
int a[n];
cout << "\nEnter Array Element :: ";
for(int i=0;i<n;i++)
cin >> a[i];
cout << "\nEnter a value :: ";
cin >> value;
int mn = minimum_length(a, n, value);
cout << "\nMinimum Length :: " << mn << "\n";
return 0;
}
Comments
Post a Comment