- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 64 lines of C++ from the credited upstream file maximum-subarray-sum-after-at-most-k-swaps.cpp.
- The implementation visibly relies on sequence storage, work queue, cached states.
- 5 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long maxSum(vector<int>& nums, int k) {8 const auto& update = [&](auto& heap, int64_t total, int x) {9 if (k == 0) {10 return total;11 }12 heap.emplace(x);13 total += x;14 if (size(heap) == k + 1) {15 total -= heap.top(); heap.pop();16 }17 return total;18 };19 20 const auto& cnt = accumulate(cbegin(nums), cend(nums), 0, [](const auto& accu, const auto& x) {21 return accu + (x < 0 ? 1 : 0);22 });23 if (cnt == size(nums)) {24 return ranges::max(nums);25 }26 if (cnt <= k) { 27 return accumulate(cbegin(nums), cend(nums), 0LL, [](const auto& accu, const auto& x) {28 return accu + (x >= 0 ? x : 0);29 });30 }31 vector<int64_t> prefix(size(nums) + 1);32 for (int i = 0; i < size(nums); ++i) {33 prefix[i + 1] = prefix[i] + nums[i];34 }35 int64_t result = 0;36 vector<int64_t> dp(size(nums));37 for (int i = 0; i < size(nums); ++i) {38 priority_queue<int, vector<int>, greater<int>> max_heap;39 int64_t total1 = 0;40 for (int j = i; j < size(nums); ++j) {41 if (nums[j] < 0) {42 total1 = update(max_heap, total1, -nums[j]);43 }44 dp[j] = -total1;45 }46 priority_queue<int, vector<int>, greater<int>> min_heap;47 int64_t total2 = 0;48 for (int j = 0; j < i; ++j) {49 if (nums[j] >= 0) {50 total2 = update(min_heap, total2, nums[j]);51 }52 }53 for (int j = size(nums) - 1; j >= i; --j) {54 result = max(result, (prefix[j + 1] - prefix[i]) - dp[j] + total2);55 if (nums[j] >= 0) {56 total2 = update(min_heap, total2, nums[j]);57 result = max(result, total2);58 }59 }60 }61 return result;62 }63};64