-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPick Max Toys of 2 Distinct Types.java
50 lines (47 loc) · 1.13 KB
/
Pick Max Toys of 2 Distinct Types.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
import java.util.*;
public class Solution {
public static void main(String[] args) {
int arr = maxToysWithTwoDistinctTypes("xxxxxxyy");
System.out.print(arr);
}
public static int maxToysWithTwoDistinctTypes(String s) {
int res =0;
int[] table = new int[26];
int l = s.length();
int ch;
int start = 0;
for(int end=0;end<l;end++)
{
ch = s.charAt(end) - 'a';
table[ch]++;
if(mapSize(table) == 2)
{
res = Math.max(res, mapCount(table));
}
else if(mapSize(table) > 2)
{
while(mapSize(table) > 2)
table[s.charAt(start++) - 'a']--;
}
}
return res;
}
public static int mapCount(int[] arr)
{
int res =0;
for(int i=0;i<arr.length;i++)
{
res += arr[i];
}
return res;
}
public static int mapSize(int[] arr)
{
int size =0;
for(int i=0;i<arr.length;i++)
{
if(arr[i] != 0)size++;
}
return size;
}
}