LeetCode 2866: Beautiful Towers II Solution
Master LeetCode problem 2866 (Beautiful Towers II), 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.
2866. Beautiful Towers II
Problem Explanation
Explanation:
To solve this problem, we need to find a beautiful configuration of towers that maximizes the sum of heights. A configuration is considered beautiful if it satisfies the conditions given in the problem description.
We can approach this problem by iterating through the array and finding the peak index where the mountain pattern changes. Then, we can assign heights to the towers in a way that the conditions are satisfied.
Here is the step-by-step algorithm:
- Iterate through the array to find the peak index where the mountain pattern changes. Let this index be
peakIndex. - Assign heights for towers from index 0 to
peakIndexin non-decreasing order (starting from 1). - Assign heights for towers from
peakIndexto the end in non-increasing order (starting from the minimum ofmaxHeights[peakIndex]andmaxHeights[peakIndex+1]).
Time Complexity: O(n) where n is the number of elements in the input array. Space Complexity: O(n) for storing the heights of towers.
:
Solution Code
class Solution {
public int maxSum(int[] maxHeights) {
int n = maxHeights.length;
int peakIndex = 0;
for (int i = 1; i < n; i++) {
if (maxHeights[i] > maxHeights[i - 1]) {
peakIndex = i;
}
}
int[] heights = new int[n];
int minHeight = Math.min(maxHeights[peakIndex], peakIndex < n - 1 ? maxHeights[peakIndex + 1] : Integer.MAX_VALUE);
for (int i = 0; i <= peakIndex; i++) {
heights[i] = i + 1;
}
for (int i = peakIndex + 1; i < n; i++) {
heights[i] = Math.max(minHeight, 1);
}
int sum = 0;
for (int height : heights) {
sum += height;
}
return sum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2866 (Beautiful Towers II)?
This page provides optimized solutions for LeetCode problem 2866 (Beautiful Towers II) 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 2866 (Beautiful Towers II)?
The time complexity for LeetCode 2866 (Beautiful Towers II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2866 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2866 in Java, C++, or Python.