Skip to content

Commit 0db6e1f

Browse files
authored
Create SllidingWindow.java
1 parent a163816 commit 0db6e1f

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

SllidingWindow.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// 1st question using sliding window technique
2+
// 1st
3+
// MAXIMUM SUM SUB ARRAY OF SIZE K : using sliding window technique
4+
class GFG {
5+
// Returns maximum sum in
6+
// a subarray of size k.
7+
static int maxSum(int arr[], int n, int k)
8+
{
9+
// Initialize result
10+
int max_sum = Integer.MIN_VALUE;
11+
12+
// Consider all blocks starting with i.
13+
for (int i = 0; i < n - k + 1; i++) {
14+
int current_sum = 0;
15+
for (int j = 0; j < k; j++)
16+
current_sum = current_sum + arr[i + j];
17+
18+
// Update result if required.
19+
max_sum = Math.max(current_sum, max_sum);
20+
}
21+
22+
return max_sum;
23+
}
24+
25+
// Driver code
26+
public static void main(String[] args)
27+
{
28+
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
29+
int k = 4;
30+
int n = arr.length;
31+
System.out.println(maxSum(arr, n, k));
32+
}
33+
}
34+
35+
// 2nd question using sliding window technique
36+
// 2nd
37+
// Longest Substring Without Repeating Characters: using sliding window technique
38+
import java.util.*;
39+
40+
public class GfG {
41+
42+
// Function to find the length of the longest
43+
// substring without repeating characters
44+
static int longestUniqueSubstr(String s) {
45+
int n = s.length();
46+
int res = 0;
47+
48+
for (int i = 0; i < n; i++) {
49+
50+
// Initializing all characters as not visited
51+
boolean[] visited = new boolean[256];
52+
53+
for (int j = i; j < n; j++) {
54+
55+
// If current character is visited,
56+
// Break the loop
57+
if (visited[s.charAt(j)]) {
58+
break;
59+
}
60+
else {
61+
62+
// Else update the result if this
63+
// window is larger, and mark current
64+
// character as visited.
65+
res = Math.max(res, j - i + 1);
66+
visited[s.charAt(j)] = true;
67+
}
68+
}
69+
}
70+
return res;
71+
}
72+
73+
public static void main(String[] args) {
74+
String s = "geeksforgeeks";
75+
System.out.println(longestUniqueSubstr(s));
76+
}
77+
}

0 commit comments

Comments
 (0)