Skip to content

Commit 79630ba

Browse files
authored
2022-08-30 update: added "Longest Subsequence With Limited Sum" (#77)
1 parent a32c1c3 commit 79630ba

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import java.util.Arrays;
4+
5+
public class LongestSubsequenceWithLimitedSum {
6+
7+
private final int[] nums;
8+
private final int[] queries;
9+
10+
public LongestSubsequenceWithLimitedSum(int[] nums, int[] queries) {
11+
this.nums = nums;
12+
this.queries = queries;
13+
}
14+
15+
public int[] solution() {
16+
int[] result = new int[queries.length];
17+
Arrays.sort(nums);
18+
for (int i = 0; i < queries.length; i++) {
19+
int sum = 0;
20+
int j;
21+
for (j = 0; j < nums.length; j++) {
22+
int num = nums[j];
23+
if (sum + num > queries[i]) {
24+
result[i] = j;
25+
break;
26+
}
27+
sum += num;
28+
}
29+
if (j == nums.length) {
30+
result[i] = j;
31+
}
32+
}
33+
return result;
34+
}
35+
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertArrayEquals;
6+
7+
public class LongestSubsequenceWithLimitedSumTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertArrayEquals(
12+
new int[]{2, 3, 4},
13+
new LongestSubsequenceWithLimitedSum(
14+
new int[]{4, 5, 2, 1},
15+
new int[]{3, 10, 21}
16+
).solution()
17+
);
18+
}
19+
20+
}

0 commit comments

Comments
 (0)