Skip to content

Commit 42b4851

Browse files
authored
Create Constrained Subsequence Sum.java
1 parent b99d324 commit 42b4851

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Hard/Constrained Subsequence Sum.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public int constrainedSubsetSum(int[] nums, int k) {
3+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
4+
pq.add(new int[]{nums[0], 0});
5+
int result = nums[0];
6+
for (int i = 1; i < nums.length; i++) {
7+
while (i - pq.peek()[1] > k) {
8+
pq.remove();
9+
}
10+
int curr = Math.max(0, pq.peek()[0]) + nums[i];
11+
result = Math.max(result, curr);
12+
pq.add(new int[]{curr, i});
13+
}
14+
return result;
15+
}
16+
}

0 commit comments

Comments
 (0)