Peak Tower Configuration with Height Limits
Stacks & QueuesAuto-graded · 26 test casesLast updated
Construct a sequence that rises then falls while respecting per-element caps, maximizing the sum using greedy peak selection and monotonic stacks.
You are designing a skyline consisting of n towers positioned at indices 0 through n - 1. Each tower i has a regulatory height limit caps[i], and you must assign it an integer height h[i] satisfying 1 <= h[i] <= caps[i].
The skyline must form a peak shape: there must exist some index peak where:
- Heights are non-decreasing from the start up to
peak:h[0] <= h[1] <= ... <= h[peak] - Heights are non-increasing from
peakto the end:h[peak] >= h[peak+1] >= ... >= h[n-1]
Note that consecutive towers may have equal heights, and the peak can be at either end (making the entire sequence non-increasing or non-decreasing).
Your task is to find the maximum possible sum of all tower heights.
Constraints
1 <= n <= 1000wheren = len(caps)1 <= caps[i] <= 10^9- The result may exceed 32-bit integers (up to approximately
10^12) but will fit in a 64-bit integer
Examples
Example 1
Input: peak_tower_sum([5, 3, 4, 1, 1])
Output: 13
Example 2
Input: peak_tower_sum([6, 5, 3, 9, 2, 7])
Output: 22
Example 3
Input: peak_tower_sum([3, 2, 5, 5, 2, 3])
Output: 18
Hints
Hint 1
Try fixing the peak position first. Once you choose which tower is tallest, how should you set the other heights?
Hint 2
For a fixed peak, each tower should be as tall as possible while respecting both its own cap and the peak constraint. This means taking the minimum of all caps between that tower and the peak.
Hint 3
A naive approach checking all peak positions takes O(n²). Can you use a monotonic stack to compute prefix minimums efficiently and achieve O(n) time?
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to enumerate all possible peak positions and compute the optimal configuration for each one.
Greedy assignment for a fixed peak: Once we designate tower p as the peak, the optimal heights are determined:
- The peak tower itself should use its full cap
caps[p] - Each tower to the left of the peak should be as tall as possible while not exceeding any cap between it and the peak (due to the non-decreasing constraint)
- Each tower to the right should similarly be limited by the minimum cap between the peak and itself
Mathematically, for peak at position p:
- Tower
j < pgets heightmin(caps[j], caps[j+1], ..., caps[p]) - Tower
k > pgets heightmin(caps[p], caps[p+1], ..., caps[k])
Why this is optimal: Any valid peak configuration must satisfy these constraints as upper bounds. Our greedy assignment achieves all these bounds simultaneously, so no other assignment can do better for the same peak.
Efficient computation with monotonic stacks: Computing running minimums naively for each peak takes O(n²). Instead, we make two passes:
-
Left-to-right pass: Build an array
left_sum[i]storing the sum of optimal heights from position 0 toiwheniis the peak, using a monotonic stack to track running minimums in O(n) total time. -
Right-to-left pass: Compute the right-side sum on the fly and combine with
left_sum[i]to get the total for each peak (subtracting the peak once since it appears in both sums).
The monotonic stack maintains indices in non-decreasing order of caps. Each index "owns" a segment where it represents the minimum cap, contributing cap × segment_length to the running sum.
Complexity
- Time: O(n). Each position is pushed and popped from the stack at most once per pass.
- Space: O(n) for the
left_sumarray and stack.
Solution
def peak_tower_sum(caps):
n = len(caps)
left_sum = [0] * n
stack = []
running = 0
for i, cap in enumerate(caps):
while stack and caps[stack[-1]] > cap:
j = stack.pop()
below = stack[-1] if stack else -1
running -= caps[j] * (j - below)
below = stack[-1] if stack else -1
running += cap * (i - below)
stack.append(i)
left_sum[i] = running
max_total = 0
stack = []
running = 0
for i in range(n - 1, -1, -1):
cap = caps[i]
while stack and caps[stack[-1]] > cap:
j = stack.pop()
above = stack[-1] if stack else n
running -= caps[j] * (above - j)
above = stack[-1] if stack else n
running += cap * (above - i)
stack.append(i)
max_total = max(max_total, left_sum[i] + running - cap)
return max_total