LeetCode 2865: Beautiful Towers I Solution

Master LeetCode problem 2865 (Beautiful Towers I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2865. Beautiful Towers I

Problem Explanation

Explanation

To solve this problem, we need to find the maximum possible sum of heights of a mountain-shaped tower arrangement. The idea is to iterate through the array and for each tower, we calculate the maximum sum of heights of the mountain-shaped tower arrangement with the peak at that tower. We can do this by considering two parts: the increasing heights to the left of the peak and the decreasing heights to the right of the peak.

  1. We can use dynamic programming to keep track of the maximum sum of heights for the increasing sequence till each tower.
  2. Similarly, we can use dynamic programming to keep track of the maximum sum of heights for the decreasing sequence from each tower.

By iterating through all towers and considering each tower as the peak, we can find the maximum sum of heights for a mountain-shaped tower arrangement.

Solution Code

class Solution {
    public int mountainTowerSum(int[] heights) {
        int n = heights.length;
        int[] increasing = new int[n];
        int[] decreasing = new int[n];
        
        increasing[0] = heights[0];
        for (int i = 1; i < n; i++) {
            increasing[i] = Math.max(increasing[i - 1], heights[i]);
        }
        
        decreasing[n - 1] = heights[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            decreasing[i] = Math.max(decreasing[i + 1], heights[i]);
        }
        
        int maxSum = 0;
        for (int i = 0; i < n; i++) {
            int peakSum = heights[i] + Math.min(increasing[i], decreasing[i]) - heights[i];
            maxSum = Math.max(maxSum, peakSum);
        }
        
        return maxSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2865 (Beautiful Towers I)?

This page provides optimized solutions for LeetCode problem 2865 (Beautiful Towers I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2865 (Beautiful Towers I)?

The time complexity for LeetCode 2865 (Beautiful Towers I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2865 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2865 in Java, C++, or Python.

Back to LeetCode Solutions