[LeetCode] Constrained Subsequence Sum

1425. Constrained Subsequence Sum

Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

  • Time : O(nlogk)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int constrainedSubsetSum(vector<int>& nums, int k) {
int n = nums.size(), res = nums.back();
priority_queue<pair<int,int>> pq;
pq.push({0,n});
for(int i = n - 1; i >= 0; i--) {
while(pq.top().second > i + k) {
pq.pop();
}
int sum = max(pq.top().first + nums[i], nums[i]);

//optimize priority queue operation
int limit = max(sum,0);
while(!pq.empty() and pq.top().first <= limit) pq.pop();
pq.push({limit, i});

res = max(res, sum);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/constrained-subsequence-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.