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.
- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- 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.
Use this to learn the idea, then write your own version.
123 45class BIT {6public:7 BIT(int n) : bit_(n + 1) { 8 }9 10 void add(int i, int64_t val) {11 ++i;12 for (; i < size(bit_); i += lower_bit(i)) {13 bit_[i] = max(bit_[i], val); 14 }15 }16 17 int64_t query(int i) const {18 ++i;19 int64_t total = 0;20 for (; i > 0; i -= lower_bit(i)) {21 total = max(total, bit_[i]); 22 }23 return total;24 }25 26private:27 inline int lower_bit(int i) const {28 return i & -i;29 }30 31 vector<int64_t> bit_;32};33 34class Solution {35public:36 long long maxAlternatingSum(vector<int>& nums, int k) {37 vector<int> sorted_nums(nums);38 ranges::sort(sorted_nums);39 sorted_nums.erase(unique(begin(sorted_nums), end(sorted_nums)), end(sorted_nums));40 unordered_map<int, int> val_to_idx;41 for (int i = 0; i < size(sorted_nums); ++i) {42 val_to_idx[sorted_nums[i]] = i;43 }44 vector<BIT> bit(2, BIT(size(val_to_idx)));45 vector<vector<int64_t>> dp(2, vector<int64_t>(size(nums)));46 for (int i = 0; i < size(nums); ++i) {47 if (i - k >= 0) {48 const auto& idx = val_to_idx[nums[i - k]];49 bit[0].add(idx, dp[0][i - k]);50 bit[1].add((size(val_to_idx) - 1) - idx, dp[1][i - k]);51 }52 const auto& idx = val_to_idx[nums[i]];53 dp[1][i] = bit[0].query(idx - 1) + nums[i];54 dp[0][i] = bit[1].query(((size(val_to_idx) - 1) - idx) - 1) + nums[i];55 }56 return max(ranges::max(dp[0]), ranges::max(dp[1]));57 }58};59