-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRomaAndChangingSigns.java
70 lines (62 loc) · 1.43 KB
/
RomaAndChangingSigns.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/** https://codeforces.com/problemset/problem/262/B #greedy #sorting */
import java.util.Arrays;
import java.util.Scanner;
class RomaAndChangingSigns {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// calculate
for (int i = 0; i < n && k > 0; i++, k--) {
if (arr[i] >= 0) {
break;
}
arr[i] *= -1;
}
if (k % 2 == 1) {
Arrays.sort(arr);
arr[0] *= -1;
}
// result
int ret = 0;
for (int a : arr) {
ret += a;
}
System.out.println(ret);
}
// O(n)
public static void betterSolution() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
sum += arr[i];
}
// calculate
int lastNeg = -1;
for (int i = 0; i < n && k > 0; i++, k--) {
if (arr[i] >= 0) {
break;
}
sum -= 2 * arr[i];
lastNeg = i;
}
if (k % 2 == 1) {
if (lastNeg == -1) {
sum -= 2 * arr[0];
} else if (lastNeg == n - 1) {
sum += 2 * arr[n - 1];
} else {
sum -= 2 * Math.min(Math.abs(arr[lastNeg]), Math.abs(arr[lastNeg + 1]));
}
}
System.out.println(sum);
}
}