forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestSubsequenceWithLimitedSum.java
46 lines (40 loc) · 1.52 KB
/
LongestSubsequenceWithLimitedSum.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
// https://leetcode.com/problems/longest-subsequence-with-limited-sum
// T: O((n + m) log(n))
// S: O(n)
import java.util.PriorityQueue;
import java.util.Queue;
public class LongestSubsequenceWithLimitedSum {
public int[] answerQueries(int[] nums, int[] queries) {
final int[] result = new int[queries.length];
final int[] prefixSumArray = getMinSumArray(nums);
for (int index = 0 ; index < queries.length ; index++) {
int maxLen = binarySearch(prefixSumArray, queries[index]);
if (maxLen < prefixSumArray.length && prefixSumArray[maxLen] == queries[index]) {
result[index] = maxLen + 1;
} else result[index] = maxLen;
}
return result;
}
private int binarySearch(int[] array, int x) {
int left = 0, right = array.length - 1, index = 0;
while (left <= right) {
index = left + (right - left) / 2;
if (array[index] == x) return index;
else if (array[index] > x) right = index - 1;
else left = index + 1;
}
return left;
}
private int[] getMinSumArray(int[] array) {
final Queue<Integer> minHeap = new PriorityQueue<>();
final int[] result = new int[array.length];
for (int element : array) {
minHeap.add(element);
}
result[0] = minHeap.poll();
for (int index = 1 ; index < result.length ; index++) {
result[index] = result[index - 1] + minHeap.poll();
}
return result;
}
}