-
Notifications
You must be signed in to change notification settings - Fork 66
/
SlidingWindow.java
52 lines (45 loc) · 1.33 KB
/
SlidingWindow.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* This program prints the maximum no. of elements with the given target sum
* This program demonstrates the Sliding Window Algorithm
* Enter the array such that a[i]>0 (0>=i<a.length())
* All the elements of the array should be positive integers
*
*/
import java.util.*;
public class SlidingWindow
{public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array size:");
int n=sc.nextInt();
System.out.println("Enter the array elements(only positive integers should be entered ):");
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter the target sum:");
int l=sc.nextInt();
int i=0,j=0;
int sum=0;
int max=0;
while(j<a.length)
{sum=sum+a[j];
if(sum==l)
{int k=j-i+1;
if(max<k)
{max=k;}
j++;
}
else if(sum<l)
{
j++; }
else if(sum>l)
{ while(sum>l)
{ sum=sum-a[i];
i++;}
j++;
}
}
System.out.println("Max no. of elements in array which make up the sum "+l+" = "+max);
sc.close();
}
}