Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 3e89514

Browse files
committedApr 14, 2025
Add solution #1425
1 parent 1762b78 commit 3e89514

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,298 LeetCode solutions in JavaScript
1+
# 1,299 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1090,6 +1090,7 @@
10901090
1422|[Maximum Score After Splitting a String](./solutions/1422-maximum-score-after-splitting-a-string.js)|Easy|
10911091
1423|[Maximum Points You Can Obtain from Cards](./solutions/1423-maximum-points-you-can-obtain-from-cards.js)|Medium|
10921092
1424|[Diagonal Traverse II](./solutions/1424-diagonal-traverse-ii.js)|Medium|
1093+
1425|[Constrained Subsequence Sum](./solutions/1425-constrained-subsequence-sum.js)|Hard|
10931094
1431|[Kids With the Greatest Number of Candies](./solutions/1431-kids-with-the-greatest-number-of-candies.js)|Easy|
10941095
1436|[Destination City](./solutions/1436-destination-city.js)|Easy|
10951096
1437|[Check If All 1's Are at Least Length K Places Away](./solutions/1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 1425. Constrained Subsequence Sum
3+
* https://leetcode.com/problems/constrained-subsequence-sum/
4+
* Difficulty: Hard
5+
*
6+
* Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence
7+
* of that array such that for every two consecutive integers in the subsequence, nums[i] and
8+
* nums[j], where i < j, the condition j - i <= k is satisfied.
9+
*
10+
* A subsequence of an array is obtained by deleting some number of elements (can be zero) from the
11+
* array, leaving the remaining elements in their original order.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var constrainedSubsetSum = function(nums, k) {
20+
const maxSums = [...nums];
21+
const deque = [];
22+
let result = nums[0];
23+
24+
for (let i = 0; i < nums.length; i++) {
25+
while (deque.length && deque[0] < i - k) {
26+
deque.shift();
27+
}
28+
29+
if (deque.length) {
30+
maxSums[i] = Math.max(maxSums[i], maxSums[deque[0]] + nums[i]);
31+
}
32+
33+
while (deque.length && maxSums[deque[deque.length - 1]] <= maxSums[i]) {
34+
deque.pop();
35+
}
36+
37+
deque.push(i);
38+
result = Math.max(result, maxSums[i]);
39+
}
40+
41+
return result;
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.