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
- 43 lines of Python from the credited upstream file maximum-sum-of-alternating-subsequence-with-distance-at-least-k.py.
- The implementation visibly relies on sequence storage, ordered lookup, cached states.
- No explicit 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(object): 6 def __init__(self, n):7 self.__bit = [0]*(n+1) 8 9 def add(self, i, val):10 i += 1 11 while i < len(self.__bit):12 self.__bit[i] = max(self.__bit[i], val) 13 i += (i & -i)14 15 def query(self, i):16 i += 1 17 ret = 018 while i > 0:19 ret = max(ret, self.__bit[i]) 20 i -= (i & -i)21 return ret22 23 24class Solution(object):25 def maxAlternatingSum(self, nums, k):26 """27 :type nums: List[int]28 :type k: int29 :rtype: int30 """31 val_to_idx = {x:i for i, x in enumerate(sorted(set(nums)))}32 bit = [BIT(len(val_to_idx)) for _ in xrange(2)]33 dp = [[0]*len(nums) for _ in xrange(2)]34 for i in xrange(len(nums)):35 if i-k >= 0:36 idx = val_to_idx[nums[i-k]]37 bit[0].add(idx, dp[0][i-k])38 bit[1].add((len(val_to_idx)-1)-idx, dp[1][i-k])39 idx = val_to_idx[nums[i]]40 dp[1][i] = bit[0].query(idx-1)+nums[i]41 dp[0][i] = bit[1].query(((len(val_to_idx)-1)-idx)-1)+nums[i]42 return max(max(dp[0]), max(dp[1]))43