LCP.P40[心算挑战]

方法一:排序+贪心

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
class Solution {

int[] cards;
int cnt, n;

public int maxmiumScore(int[] cards, int cnt) {
this.cards = cards;
this.cnt = cnt;
Arrays.sort(cards);
this.n = cards.length;
int sum = 0;
for (int i = n - cnt; i < n; ++i) {
sum += cards[i];
}
if (sum % 2 == 0) return sum;

int x = cards[n - cnt];
int ans = replaceSum(sum, x);
for (int i = n - cnt + 1; i < n; ++i) {
if (cards[i] % 2 != x % 2) { // 找到一个最小的奇偶性和 x 不同的数
ans = Math.max(ans, replaceSum(sum, cards[i]));
break;
}
}
return ans;
}

private int replaceSum(int sum, int x) {
for (int i = n - cnt - 1; i >= 0; --i) {
if (cards[i] % 2 != x % 2) { // 找到一个最大的奇偶性和 x 不同的数
return sum - x + cards[i];
}
}
return 0;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(logn)$