Peak Subsequence Maximum Sum
Dynamic ProgrammingAuto-graded · 20 test casesLast updated
Tests dynamic programming with coordinate compression and Fenwick trees to efficiently compute optimal bitonic subsequences.
Peak Subsequence Maximum Sum
Given an array of positive integers representing building heights, find the maximum sum of a subsequence that forms a bitonic pattern: values that are non-decreasing up to some peak element, then non-increasing after the peak.
A valid peak subsequence must:
- Maintain the relative order of elements from the original array
- Have values that never decrease until reaching a peak index
- Have values that never increase after the peak index
- Contain at least one element (which serves as both the start and peak)
Equal consecutive values are allowed on both the ascending and descending sides.
Write a function that returns the maximum possible sum of heights in such a subsequence.
Constraints
1 <= len(heights) <= 10^51 <= heights[i] <= 10^9- All values are positive integers
Examples
Example 1
Input: peak_subsequence_sum([1, 5, 2, 7, 3])
Output: 16
Example 2
Input: peak_subsequence_sum([10, 20, 10])
Output: 40
Hints
Hint 1
Consider each position as a potential peak and compute the best ascending path ending there and best descending path starting there
Hint 2
Use dynamic programming where dp_up[i] represents the maximum sum of a non-decreasing subsequence ending at index i, and dp_down[i] represents the maximum sum of a non-increasing subsequence starting at index i
Hint 3
A Fenwick tree (Binary Indexed Tree) with coordinate compression can answer range maximum queries efficiently, reducing the solution from O(n²) to O(n log n)
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to treat each array position as a potential peak of the bitonic subsequence. For a valid peak at index p, we need:
- The maximum sum of a non-decreasing subsequence from the left that ends at
p - The maximum sum of a non-increasing subsequence from the right that starts at
p
We solve this with dynamic programming:
-
Left sweep (ascending phase): Compute
dp_up[i]= maximum sum of a non-decreasing subsequence ending at indexi. The recurrence is:dp_up[i] = heights[i] + max(dp_up[j])over allj < iwhereheights[j] <= heights[i]. -
Right sweep (descending phase): Compute
dp_down[i]= maximum sum of a non-increasing subsequence starting at indexi. The recurrence is:dp_down[i] = heights[i] + max(dp_down[j])over allj > iwhereheights[j] <= heights[i]. -
Combine: For each potential peak at index
i, the total sum isdp_up[i] + dp_down[i] - heights[i]. We subtractheights[i]because it appears in both the ascending and descending paths.
The naive implementation takes O(n²) time. To optimize, observe that the inner step—finding the maximum dp_up[j] among earlier indices with heights[j] <= heights[i]—is a prefix maximum query over value ranges.
Optimization with Fenwick Tree:
- Use coordinate compression to map values to ranks
1..mwheremis the number of distinct values - Maintain a Fenwick tree (Binary Indexed Tree) that stores prefix maximums indexed by value rank
- For each position, query the maximum among all ranks up to the current value's rank, then update that rank with the new dp value
- This reduces each dp computation from O(n) to O(log n)
Why It Works
The approach relies on optimal substructure: if an optimal non-decreasing path ends at position i with a previous element at j, then the prefix up to j must itself be optimal for ending at j. Otherwise, we could substitute a better prefix and improve the total.
Since we process indices sequentially and query only previously computed values, the Fenwick tree always contains exactly the information needed to make optimal choices. The use of value ranks as the tree index ensures that querying rank r returns the best result from all previous positions with values in the allowed range.
Complexity
Time: O(n log n)
- Coordinate compression via sorting: O(n log n)
- Two passes over the array, each with O(log n) Fenwick operations per element: O(n log n)
Space: O(n)
- Storage for ranks, dp arrays, and Fenwick trees: O(n + m) where m ≤ n
Note: Sums can reach approximately 10^5 × 10^9 = 10^14, which fits comfortably in Python integers.
Solution Code
from typing import List
def peak_subsequence_sum(heights: List[int]) -> int:
n = len(heights)
if n == 0:
return 0
# Coordinate compression: map each unique value to a rank
unique_vals = sorted(set(heights))
value_to_rank = {val: idx + 1 for idx, val in enumerate(unique_vals)}
num_ranks = len(unique_vals)
def fenwick_query(tree, idx):
"""Query maximum value in range [1, idx]"""
result = 0
while idx > 0:
result = max(result, tree[idx])
idx -= idx & -idx
return result
def fenwick_update(tree, idx, val):
"""Update position idx with maximum of current and new value"""
while idx <= num_ranks:
tree[idx] = max(tree[idx], val)
idx += idx & -idx
# Compute dp_up[i]: max sum of non-decreasing subsequence ending at i
dp_up = [0] * n
fenwick_up = [0] * (num_ranks + 1)
for i in range(n):
h = heights[i]
r = value_to_rank[h]
# Query best sum ending at any value <= current height
dp_up[i] = h + fenwick_query(fenwick_up, r)
fenwick_update(fenwick_up, r, dp_up[i])
# Compute dp_down[i] and find maximum peak sum in one pass
max_sum = 0
fenwick_down = [0] * (num_ranks + 1)
for i in range(n - 1, -1, -1):
h = heights[i]
r = value_to_rank[h]
# Query best sum starting at any value <= current height
dp_down = h + fenwick_query(fenwick_down, r)
fenwick_update(fenwick_down, r, dp_down)
# Peak at i: combine ascending path to i and descending path from i
# Subtract h once since it's counted in both dp_up[i] and dp_down
max_sum = max(max_sum, dp_up[i] + dp_down - h)
return max_sum