public class FindMinimumLengthSubArrayWithSumK {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {2,3,1,1,-1,6,4,2,1,8};
int val = 7;
findLength(arr, val);
}
public static void findLength(int[] arr, int val) {
int start=0;
int end=0;
int finalCount = arr.length;
for(int i=0;i<arr.length;i++) {
int sum = 0;
int count = 0;
for(int j=i;j<arr.length;j++) {
sum+= arr[j];
count++;
if(sum==val && count<finalCount) {
start = i;
end = j;
finalCount = count;
break;
}
}
}
System.out.println("start::"+start);
System.out.println("end::"+end);
System.out.println("final count::"+finalCount);
}
}
output::
start::6
end::8
final count::3
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {2,3,1,1,-1,6,4,2,1,8};
int val = 7;
findLength(arr, val);
}
public static void findLength(int[] arr, int val) {
int start=0;
int end=0;
int finalCount = arr.length;
for(int i=0;i<arr.length;i++) {
int sum = 0;
int count = 0;
for(int j=i;j<arr.length;j++) {
sum+= arr[j];
count++;
if(sum==val && count<finalCount) {
start = i;
end = j;
finalCount = count;
break;
}
}
}
System.out.println("start::"+start);
System.out.println("end::"+end);
System.out.println("final count::"+finalCount);
}
}
output::
start::6
end::8
final count::3
No comments:
Post a Comment