forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslding_window_technique.java
More file actions
91 lines (79 loc) · 2.35 KB
/
slding_window_technique.java
File metadata and controls
91 lines (79 loc) · 2.35 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Given an array of N elements and a value K (K <= N) , calculate maximum summation of K consecutive elements in the array.
We can solve this problem by using Sliding Window Technique.
This technique will allow us to solve this problem in O(N)
*/
import java.util.Scanner;
import java.lang.*;
public class SlidingWindow
{
// this function will give us the maximum sum
static int max_sum_by_sliding_window(int ar[] , int number , int K)
{
int final_sum = 0;
if(number == K)
{
int sum = 0;
// max_sum will be the sum of all elements of array.
for(int i = 0; i < number; i++)
{
sum += ar[i];
}
final_sum = sum;
}
if(number > K)
{
// calculate sum of first window of size K
int max_sum = 0, win_sum = 0;
for(int i = 0; i < K; i++)
{
max_sum += ar[i];
}
/* calculate sum of remaining windows
by removing elements from first window simultaneously add elements to current window */
win_sum = max_sum;
for(int i = K; i < number; i++)
{
win_sum += (ar[i] - ar[i - K]);
if(win_sum > max_sum)
{
max_sum = win_sum;
}
}
final_sum = max_sum;
}
return final_sum;
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of array \n");
int number = scan.nextInt();
int K = scan.nextInt();
int[] ar = new int[number];
System.out.println("Enter array elements \n");
for(int i = 0; i < number; i++)
{
ar[i] = scan.nextInt();
}
int solve = max_sum_by_sliding_window(ar, number , K);
System.out.print("maximum summation of K consecutive elements in the array is ");
System.out.println(solve);
scan.close();
}
}
/*
Standard Input and Output
1. if N == K
Input array size and value
5 5
1 2 3 4 5
maximum summation of K consecutive elements in the array is 15
2. if N > K
Input array size and value
5 3
5 2 -1 0 3
maximum summation of K consecutive elements in the array is 6
Time Complexity : O(N)
Space Complexity : O(1)
*/