KatInterview

Peak Subsequence Maximum Sum

Dynamic ProgrammingAuto-graded · 20 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingfenwick-treecoordinate-compression

Last 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^5
  • 1 <= 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)