-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-46.java
More file actions
35 lines (29 loc) · 941 Bytes
/
leet-code-q-46.java
File metadata and controls
35 lines (29 loc) · 941 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
import java.util.*;
class Solution {
public long maximumTotalDamage(int[] power) {
if (power.length == 0) return 0;
Arrays.sort(power);
List<Integer> vals = new ArrayList<>();
List<Long> earn = new ArrayList<>();
for (int i = 0; i < power.length; ) {
int v = power[i];
long sum = 0;
while (i < power.length && power[i] == v) {
sum += v;
i++;
}
vals.add(v);
earn.add(sum);
}
int n = vals.size();
long[] dp = new long[n + 1];
for (int i = n - 1; i >= 0; i--) {
int nextIdx = Collections.binarySearch(vals, vals.get(i) + 3);
if (nextIdx < 0) nextIdx = -nextIdx - 1;
long take = earn.get(i) + dp[nextIdx];
long skip = dp[i + 1];
dp[i] = Math.max(take, skip);
}
return dp[0];
}
}