Skip to content

LeetCode 84: Largest Rectangle in Histogram #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
dev
  • Loading branch information
DimkaGorhover committed Sep 25, 2020
commit 3b86d0144b9b0f8659caf9f7fc2ca66a0a15ea40
43 changes: 43 additions & 0 deletions src/main/java/org/gd/leetcode/p0084/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.gd.leetcode.p0084;

import org.gd.leetcode.common.LeetCode;

/**
* https://leetcode.com/problems/largest-rectangle-in-histogram/
*/
@LeetCode(
name = "Largest Rectangle in Histogram",
difficulty = LeetCode.Level.HARD,
state = LeetCode.State.TODO,
tags = {
LeetCode.Tags.ARRAY,
LeetCode.Tags.STACK
}
)
class Solution {

public int largestRectangleArea(int[] heights) {

if (heights == null || heights.length == 0)
return 0;

if (heights.length == 1)
return heights[0];

int max = 0;
for (int i = 0; i < heights.length; i++) {

max = Math.max(max, heights[i]);
int lowestHeight = heights[i];

for (int j = i + 1; j < heights.length; j++) {

int width = j - i + 1;
lowestHeight = Math.min(lowestHeight, heights[j]);
max = Math.max(max, width * lowestHeight);

}
}
return max;
}
}
26 changes: 26 additions & 0 deletions src/test/java/org/gd/leetcode/p0084/SolutionTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.gd.leetcode.p0084;

import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.*;

@DisplayName("LeetCode #84: Largest Rectangle in Histogram")
class SolutionTest {

private static Stream<Arguments> args() {
return Stream.of(
Arguments.of(new int[]{2, 1, 5, 6, 2, 3}, 10)
);
}

@ParameterizedTest
@MethodSource("args")
void largestRectangleArea(int[] area, int expected) {
assertEquals(expected, new Solution().largestRectangleArea(area));
}
}