-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStages.java
More file actions
44 lines (39 loc) · 991 Bytes
/
Stages.java
File metadata and controls
44 lines (39 loc) · 991 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
/**
* https://codeforces.com/problemset/problem/1011/A #greedy #sorting #implementation two way: sort
* the character array. or use arr[26] to store characters.
*/
import java.util.Arrays;
import java.util.Scanner;
public class Stages {
static int calMinimalWeigth() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
char[] arr = new char[n];
String s = sc.next();
arr = s.toCharArray();
Arrays.sort(arr);
int sum = (arr[0] - 'a' + 1);
if (k == 1) {
return sum;
}
int count = 1;
int result = -1;
int prevIdx = 0;
for (int i = 1; i < n; i++) {
if (arr[i] != arr[prevIdx] && arr[i] != (arr[prevIdx] + 1)) {
count += 1;
sum += (arr[i] - 'a' + 1);
prevIdx = i;
}
if (count == k) {
result = sum;
break;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(calMinimalWeigth());
}
}