Skip to content

Largest Rectangle In Histogram#128

Open
tom4649 wants to merge 2 commits into
mainfrom
84.Largest-Rectangle-in-Histogram
Open

Largest Rectangle In Histogram#128
tom4649 wants to merge 2 commits into
mainfrom
84.Largest-Rectangle-in-Histogram

Conversation

@tom4649

@tom4649 tom4649 commented Jun 4, 2026

Copy link
Copy Markdown
Owner

@@ -0,0 +1,19 @@
class Solution:
def largestRectangleArea(self, heights: list[int]) -> int:
increasing_stack: tuple[int, int] = [] # list of (height, num_greater_left)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このコメントで、num_greater_leftが何か伝わりそうでしょうか?

)
num_greater_right += num_greater_left + 1

increasing_stack.append((height, num_greater_right))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

increasing_stack: tuple[int, int] = []  # list of (height, num_greater_left)

とありますが、pushしているのは、num_greater_rightですね。これで読み手に意図は伝わりそうでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメントを日本語にして修正しました。型ヒントも間違っていましたね。

height_of_rectangle, num_greater_left = increasing_stack.pop()
largest_area = max(
largest_area,
height_of_rectangle * (num_greater_left + 1 + num_greater_right),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

スタックに高さではなく、インデックスを格納するとシンプルに計算できると思います。

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

参考:

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;
    }
};

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indexだけを入れておいても幅を計算できるのですね。最初に-1を入れておけば条件分岐もなくなりますね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants