-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFindSubsequenceOfLengthKWithTheLargestSum.java
51 lines (44 loc) · 1.55 KB
/
FindSubsequenceOfLengthKWithTheLargestSum.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
// https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum
// T: O(nloogn + klogk)
// S: o(n)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class FindSubsequenceOfLengthKWithTheLargestSum {
public int[] maxSubsequence(int[] nums, int k) {
List<Number>numbers = toNumbersList(nums);
numbers.sort(Comparator.comparingInt(a -> a.value));
List<Number> topK = getLastK(numbers, k);
topK.sort(Comparator.comparing(a -> a.index));
return toArray(topK);
}
private List<Number> toNumbersList(int[] array) {
final List<Number> numbers = new ArrayList<>(array.length);
for (int index = 0 ; index < array.length ; index++) {
numbers.add(new Number(array[index], index));
}
return numbers;
}
private List<Number> getLastK(List<Number> numbers, int k) {
final List<Number> result = new ArrayList<>();
for (int i = 0 ; i < k ; i++) {
result.add(numbers.get(numbers.size() - 1 - i));
}
return result;
}
private int[] toArray(List<Number> numbers) {
final int[] array = new int[numbers.size()];
for (int i = 0 ; i < array.length ; i++) {
array[i] = numbers.get(i).value;
}
return array;
}
private static final class Number {
private final int value;
private final int index;
private Number(int value, int index) {
this.value = value;
this.index = index;
}
}
}