-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedSubstring.java
More file actions
46 lines (42 loc) · 984 Bytes
/
BalancedSubstring.java
File metadata and controls
46 lines (42 loc) · 984 Bytes
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
/*
https://codeforces.com/problemset/problem/873/B
#implementation
max =
-----------
1 1 0 1 0 1 1 1
1 2 1 2 1 2 3 4 => gap
| 1 0 0 1
0 1 0 -1 0
BALANCE => THINK ABOUT PREFIX SUM.
A -> C <- B
=> A->B "no meaning"
*/
import java.util.Arrays;
import java.util.Scanner;
public class BalancedSubstring {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
String s = sc.next();
// other way : hash map (store only existing values)
int[] arr = new int[2 * n + 1];
Arrays.fill(arr, -1);
int idx = 0;
arr[n + 0] = 0;
// index from 1-> s.length()
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
idx++;
} else {
idx--;
}
if (arr[idx + n] == -1) {
arr[idx + n] = i + 1;
} else {
result = Math.max(result, i + 1 - arr[idx + n]);
}
}
System.out.println(result);
}
}