KatInterview

Peak Tower Configuration with Height Limits

Stacks & QueuesAuto-graded · 26 test cases
HardAuto-gradedStacks & Queuesmonotonic-stackgreedyprefix-sum

Last 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 peak to 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 <= 1000 where n = 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?