-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLongestSubsequenceWithLimitedSum.java
61 lines (52 loc) · 1.61 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*https://leetcode.com/problems/longest-subsequence-with-limited-sum/*/
class Solution {
public int[] answerQueries(int[] nums, int[] queries) {
Arrays.sort(nums);
int[] temp = new int[queries.length];
for (int i = 0; i < queries.length; ++i)
temp[i] = queries[i];
Arrays.sort(queries);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int i = 0, j = 0, sum = 0, count = 0, n = nums.length, m = queries.length;
int[] result = new int[m];
i = 0;
while (i < n && j < m)
{
if (sum+nums[i] <= queries[j])
{
sum += nums[i];
++count;
++i;
}
else
{
map.put(queries[j],count);
++j;
}
}
while (j < m)
map.put(queries[j++],count);
for (j = 0; j < queries.length; ++j)
result[j] = map.getOrDefault(temp[j],0);
return result;
}
}
class Solution {
public int[] answerQueries(int[] nums, int[] queries) {
Arrays.sort(nums);
int [] result = new int [queries.length];
int count;
int sum;
for (int i = 0; i < result.length; ++i){
count = 0;
sum = queries[i];
for (int j = 0; j < nums.length; ++j){
sum -= nums[j];
if (sum < 0) break;
++count;
}
result[i] = count;
}
return result;
}
}