给定一个整数数组nums和整数K ,任务是找到该数组的一个非空子序列的最大和,以使子序列中的每两个连续整数nums [i]和nums [j],其中i
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.
例子:
Input: nums = [10, 2, -10, 5, 20], K = 2
Output: 37
Explanation:
The subsequence is [10, 2, 5, 20].
Input: nums = [-1, -2, -3], K = 1
Output: -1
Input: nums = [10, -2, -10, -5, 20], K = 2
Output: 23
途径:
- 此问题的最佳解决方案可以通过使用“滑动窗口最大值”来实现。
- 对于每个索引,请检查从其前的大小为K的窗口可以获取的最大值。如果最大值为负,请改用零。
// C++ program to find the maximum sum
// subsequence under given constraint
#include
using namespace std;
// Function return the maximum sum
int ConstrainedSubsetSum(vector& nums,
int k)
{
deque > d;
// Iterating the given array
for (int i = 0; i < nums.size(); i++)
{
// Check if deque is empty
nums[i] += d.size()
? max(d.back().first, 0) : 0;
while (d.size() &&
d.front().first < nums[i])
d.pop_front();
d.push_front({ nums[i], i });
if (d.back().second == i - k)
d.pop_back();
}
int ans = nums[0];
for (auto x : nums)
ans = max(ans, x);
return ans;
}
// Driver code
int main()
{
vector nums = { 10, -2, -10,
-5, 20 };
int K = 2;
// Function call
cout << ConstrainedSubsetSum(nums, K)
<< endl;
return 0;
}
输出:
23
时间复杂度: O(N)
空间复杂度: O(K)