Largest Rectangle In Histogram#128
Open
tom4649 wants to merge 2 commits into
Open
Conversation
liquo-rice
reviewed
Jun 5, 2026
| @@ -0,0 +1,19 @@ | |||
| class Solution: | |||
| def largestRectangleArea(self, heights: list[int]) -> int: | |||
| increasing_stack: tuple[int, int] = [] # list of (height, num_greater_left) | |||
There was a problem hiding this comment.
このコメントで、num_greater_leftが何か伝わりそうでしょうか?
| ) | ||
| num_greater_right += num_greater_left + 1 | ||
|
|
||
| increasing_stack.append((height, num_greater_right)) |
There was a problem hiding this comment.
increasing_stack: tuple[int, int] = [] # list of (height, num_greater_left)とありますが、pushしているのは、num_greater_rightですね。これで読み手に意図は伝わりそうでしょうか?
Owner
Author
There was a problem hiding this comment.
コメントを日本語にして修正しました。型ヒントも間違っていましたね。
liquo-rice
reviewed
Jun 5, 2026
| height_of_rectangle, num_greater_left = increasing_stack.pop() | ||
| largest_area = max( | ||
| largest_area, | ||
| height_of_rectangle * (num_greater_left + 1 + num_greater_right), |
There was a problem hiding this comment.
スタックに高さではなく、インデックスを格納するとシンプルに計算できると思います。
There was a problem hiding this comment.
参考:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);
stack<int> st;
st.push(-1);
int max_area = 0;
for (int i = 0; i < heights.size(); ++i) {
while (st.top() != -1 && heights[st.top()] >= heights[i]) {
int h = heights[st.top()];
st.pop();
max_area = max(max_area, h * (i - st.top() - 1));
}
st.push(i);
}
return max_area;
}
};
Owner
Author
There was a problem hiding this comment.
indexだけを入れておいても幅を計算できるのですね。最初に-1を入れておけば条件分岐もなくなりますね。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://leetcode.com/problems/largest-rectangle-in-histogram/description/?envType=problem-list-v2&envId=rab78cw1