LeetCode 3301: Maximize the Total Height of Unique Towers Solution
Master LeetCode problem 3301 (Maximize the Total Height of Unique Towers), 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.
Problem Explanation
Explanation
To maximize the total height of unique towers, we need to assign heights to each tower such that the height of the ith tower is a positive integer and does not exceed maximumHeight[i], and no two towers have the same height. We can achieve this by sorting the maximumHeight array in descending order and then assigning heights starting from 1 to the maximum height allowed for each tower. If at any point we find that the maximum height for a tower is less than the current height we are trying to assign, we return -1 as it is not possible to assign unique heights in this scenario.
- Sort the
maximumHeightarray in descending order. - Iterate over the sorted array and assign heights from 1 upwards to each tower, making sure that the assigned height does not exceed the maximum height allowed.
- If at any point we find that the maximum height for a tower is less than the current height we are trying to assign, return -1.
- Calculate and return the total sum of tower heights.
Time complexity: O(n log n) where n is the number of elements in the maximumHeight array due to sorting.
Space complexity: O(1) as we are using constant extra space.
Solution Code
import java.util.Arrays;
class Solution {
public int maximizeTowerHeights(int[] maximumHeight) {
Arrays.sort(maximumHeight);
int n = maximumHeight.length;
int totalHeight = 0;
for (int i = 0; i < n; i++) {
int height = Math.min(i + 1, maximumHeight[i]);
if (height < i + 1) {
return -1;
}
totalHeight += height;
}
return totalHeight;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3301 (Maximize the Total Height of Unique Towers)?
This page provides optimized solutions for LeetCode problem 3301 (Maximize the Total Height of Unique Towers) 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 3301 (Maximize the Total Height of Unique Towers)?
The time complexity for LeetCode 3301 (Maximize the Total Height of Unique Towers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3301 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3301 in Java, C++, or Python.