Problem solution · C++

Maximum Sum of Alternating Subsequence with Distance at Least K

Maximum Sum of Alternating Subsequence with Distance at Least K: a C++ solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Segment tree or range structure
Source
Kamyu LeetCode Solutions
Length
59 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For Maximum Sum of Alternating Subsequence with Distance at Least K, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 59 lines of C++ from the credited upstream file maximum-sum-of-alternating-subsequence-with-distance-at-least-k.cpp.
  • The implementation visibly relies on sequence storage, hash lookup, cached states.
  • 4 loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMaximum Sum of Alternating Subsequence with Distance at Least K · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(nlogn)// Space: O(n) // sort, coordinate compression, fenwick tree, sliding window, dpclass BIT {public:    BIT(int n) : bit_(n + 1) {  // 0-indexed    }        void add(int i, int64_t val) {        ++i;        for (; i < size(bit_); i += lower_bit(i)) {            bit_[i] = max(bit_[i], val);  // modified        }    }     int64_t query(int i) const {        ++i;        int64_t total = 0;        for (; i > 0; i -= lower_bit(i)) {            total = max(total, bit_[i]);  // modified        }        return total;    } private:    inline int lower_bit(int i) const {        return i & -i;    }        vector<int64_t> bit_;}; class Solution {public:    long long maxAlternatingSum(vector<int>& nums, int k) {        vector<int> sorted_nums(nums);        ranges::sort(sorted_nums);        sorted_nums.erase(unique(begin(sorted_nums), end(sorted_nums)), end(sorted_nums));        unordered_map<int, int> val_to_idx;        for (int i = 0; i < size(sorted_nums); ++i) {            val_to_idx[sorted_nums[i]] = i;        }        vector<BIT> bit(2, BIT(size(val_to_idx)));        vector<vector<int64_t>> dp(2, vector<int64_t>(size(nums)));        for (int i = 0; i < size(nums); ++i) {            if (i - k >= 0) {                const auto& idx = val_to_idx[nums[i - k]];                bit[0].add(idx, dp[0][i - k]);                bit[1].add((size(val_to_idx) - 1) - idx, dp[1][i - k]);            }            const auto& idx = val_to_idx[nums[i]];            dp[1][i] = bit[0].query(idx - 1) + nums[i];            dp[0][i] = bit[1].query(((size(val_to_idx) - 1) - idx) - 1) + nums[i];        }        return max(ranges::max(dp[0]), ranges::max(dp[1]));    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗