-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxChocolates.java
More file actions
48 lines (42 loc) · 1.49 KB
/
Copy pathMaxChocolates.java
File metadata and controls
48 lines (42 loc) · 1.49 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
package jpmorgan;
import java.util.*;
public class MaxChocolates {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int money = sc.nextInt();
sc.nextLine();
String chocolates = sc.nextLine();
int[] costs = new int[26];
for (int i = 0; i < 26; i++) {
costs[i] = sc.nextInt();
}
System.out.println(maxChocolates(a, money, chocolates, costs));
}
public static int maxChocolates(int a, int money, String chocolates, int[] costs) {
int maxCount = 0;
for (char freeType : new HashSet<Character>() {
{
for (char ch : chocolates.toCharArray()) {
add(ch);
}
}
}) {
int totalCost = 0, start = 0;
for (int end = 0; end < chocolates.length(); end++) {
char ch = chocolates.charAt(end);
if (ch != freeType) {
totalCost += costs[ch - 'a'];
}
while (totalCost > money) {
char startChar = chocolates.charAt(start++);
if (startChar != freeType) {
totalCost -= costs[startChar - 'a'];
}
}
maxCount = Math.max(maxCount, end - start + 1);
}
}
return maxCount;
}
}