#2866
Beautiful Towers II
MediumArrayStackMonotonic StackDynamic ProgrammingTwo-Pointer Technique
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a two-pass approach to calculate the maximum possible heights for each peak. This reduces the complexity by avoiding redundant calculations and ensures we respect the mountain condition efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Create an array left that stores the maximum heights from the left up to each index.
- 2Step 2: Create an array right that stores the maximum heights from the right up to each index.
- 3Step 3: For each index i, calculate the maximum height as the minimum of left[i] and right[i].
- 4Step 4: Sum the heights to get the maximum possible sum.
solution.py20 lines
1# Full working Python code
2
3def maxBeautifulSum(maxHeights):
4 n = len(maxHeights)
5 left = [0] * n
6 right = [0] * n
7 # Fill left array
8 left[0] = maxHeights[0]
9 for i in range(1, n):
10 left[i] = min(left[i - 1], maxHeights[i])
11 # Fill right array
12 right[n - 1] = maxHeights[n - 1]
13 for i in range(n - 2, -1, -1):
14 right[i] = min(right[i + 1], maxHeights[i])
15 # Calculate maximum sum
16 max_sum = 0
17 for i in range(n):
18 max_sum += min(left[i], right[i])
19 return max_sum
20ℹ
Complexity note: The time complexity is O(n) because we traverse the array a constant number of times. The space complexity is O(n) due to the additional arrays used to store left and right heights.
- 1The peak can be any index, and the heights must respect the mountain condition.
- 2Using two arrays to track maximum heights from both sides allows efficient calculation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.