1425.cpp (523B)
1 class Solution { 2 public: 3 int constrainedSubsetSum(vector<int> &nums, int k) { 4 deque<int> q; 5 int res = nums[0]; 6 for (int i = 0; i < nums.size(); ++i) { 7 nums[i] += !q.empty() ? q.front() : 0; 8 res = max(res, nums[i]); 9 while (!q.empty() && nums[i] > q.back()) 10 q.pop_back(); 11 if (nums[i] > 0) q.push_back(nums[i]); 12 if (i >= k && !q.empty() && q.front() == nums[i - k]) q.pop_front(); 13 } 14 return res; 15 } 16 };