Python 3200.py
class Solution:
def maxHeightOfTriangle(self, red: int, blue: int) -> int:
def height(one, two):
width = 0 # same as height
while one >= width + 1:
width += 1
one -= width
one, two = two, one
return width
return max(height(red, blue), height(blue, red))
Difficulty
and has an acceptance rate of about 45% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Enumeration
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method maxHeightOfTriangle. This method receives two integer arguments, red and blue, and computes the greatest possible height of a triangle that can be built by alternately using units from the two piles. The core of the algorithm resides in a nested helper function height, which simulates the construction process for a specific ordering of the piles. The final result is the maximum height obtained from both possible orderings.
Core Logic
Helper Function Definition
def height(one, two):
width = 0
while one >= width + 1:
width += 1
one -= width
one, two = two, one
return width
The helper receives two counters, one and two, representing the current pile being consumed and the alternate pile, respectively. The variable width tracks the current level of the triangle, which also serves as the amount of material required for the next level.
Incremental Construction Loop
The while condition one >= width + 1 guarantees that the current pile has enough material to support the next level. Inside the loop, width is increased by one, reflecting the addition of a new level. The required amount (width) is then subtracted from one.
Alternating Piles
After each subtraction, the line one, two = two, one swaps the roles of the two piles. This swap models the rule that the next level must be built from the opposite pile, ensuring an alternating consumption pattern throughout the construction.
Result Extraction
When the loop can no longer continue-because the active pile lacks sufficient material-the function returns the accumulated width, which corresponds to the height achieved under the given ordering.
Edge-Case Handling
When either red or blue is zero, the first call to height receives a zero for one. The while condition fails immediately, and the function returns 0, correctly indicating that no triangle can be formed.
If one pile is significantly larger than the other, the alternating swap ensures that the smaller pile limits the height. The algorithm naturally stops when the smaller pile can no longer provide the required amount for the next level, regardless of how much material remains in the larger pile.
When both inputs are equal, the construction proceeds symmetrically, and the height achieved is the same for both orderings, resulting in the correct maximal height.
Performance Optimizations
The algorithm operates with a minimal memory footprint: only a handful of integer variables (one, two, width) are used, and no auxiliary data structures are allocated.
The use of Python’s tuple assignment for swapping (one, two = two, one) eliminates the need for a temporary variable, reducing overhead and keeping the swap operation atomic.
Incremental updates (width += 1 and one -= width) avoid recomputing the sum of the series at each step, thereby saving repeated arithmetic.
By evaluating both possible starting orders (height(red, blue) and height(blue, red)) and taking the maximum, the implementation guarantees the optimal result with only two passes through the construction loop, avoiding any redundant calculations.
Final Computation
return max(height(red, blue), height(blue, red))
The outer method invokes the helper twice, once with red as the initial active pile and once with blue as the initial active pile. The max function selects the larger height, delivering the final answer for the given inputs.
ELI5 - Simplified Explanation
Imagine building a tall tower out of shiny colored blocks. You have some red blocks and some blue blocks. The rules for building this tower are very specific. Each level of the tower needs to be one block longer than the level right below it. The first layer needs one block, the second layer needs two blocks, the third needs three blocks, and so on. Also, you must switch colors every time you add a new layer. So if you start with red on the bottom, the next layer must be blue, then red again, and so on.
The code works by testing two different versions of the tower. One version starts with a red layer on the bottom, and the other version starts with a blue layer on the bottom. The part of the code called height acts like a rule checker. It looks at how many blocks you have and starts building level by level. It keeps counting as long as there are enough blocks left to make the next layer bigger than the last one. Once there are not enough blocks to finish a new layer, it stops and tells you how high the tower grew.
Finally, the code compares the two towers built by these rules. It looks at the one started with red and the one started with blue, and it picks the one that ended up being the tallest. That gives you the total number of layers for the highest tower possible with the set of blocks provided.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | Python | Java | C++ | TS | ||
| WalkCCC | Python | Java | C++ | ||||
| leetcode.ca | Python | Java | C++ | Go | TS | ||
| Progiez | Python | Java | C++ | ||||
| github | charles-wangkai | Java | |||||
| everthis | JS | ||||||
| fsq | Python | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | Python |
Videos
Solved On The Same Day
- problem 3184: Count Pairs That Form a Complete Day I
- problem 3185: Count Pairs That Form a Complete Day II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality