Histogram, calculate the largest area

Given a histogram {1, 3, 4, 6, 2, 1, 3}, calculate the largest rectangle area.

idea: for every index(post), we are certain that this rectangle starts from index, but when does it end? if the index is something that is smaller than previous, then the rectangle ends. e.g. the given sample, when index is 5, (value is 2), rectangle starts from 1(value 3), 2(value 4), 3(value 6) ends. We can use a stack to push larger values into it and pop them out if less value is encountered until what left in the stack is smaller than the current one.

public class Histogram {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] histogram = {1, 3, 4, 6, 2, 1, 3};
System.out.println("largest area: " + getLargestArea(histogram));
}

private static Info getLargestArea(int[] histogram) {
// TODO Auto-generated method stub
Stack<Info> stack = new Stack<Info>();
List<Info> list = new ArrayList<Info>();
for (int i = 0; i < histogram.length; i++) {
Info inf = new Info(i, histogram[i]);
//we can decide left value for a post
inf.left = i;
if (stack.isEmpty() || stack.peek().value <= histogram[i]) {
stack.push(inf);
} else {
// System.out.printf("i = %d\n", i);
//stack.peek().value > histogram[i], we can
while (!stack.isEmpty() && stack.peek().value > histogram[i]) {
Info isure = stack.pop();
isure.right = i;
// System.out.println("pop: " + isure);
list.add(isure);
}
stack.push(inf);
}
}
while (!stack.isEmpty()) {
Info isure = stack.pop();
isure.right = histogram.length-1;
list.add(isure);
}
Collections.sort(list);
return list.get(0);
}

private static class Info implements Comparable {
int left = -1;
int right = -1;
int area = -1;
int index; //histogram index
int value; //histogra value

Info(int index, int value) {
this.index = index;
this.value = value;
}

public int getArea() {
if (this.area == -1) {
this.area = this.value * (this.right - this.left);
}
return this.area;
}

public int compareTo(Object o) {
// TODO Auto-generated method stub
if (o == this) return 0;
if (o instanceof Info == false) return -1;
Info inf = (Info) o;
if (getArea() < inf.getArea()) {
return 1;
} else if (getArea() > inf.getArea()) {
return -1;
} else return 0;
}

public String toString() {
return "area: " + getArea() + ", value " + value + ", from " + left + " to " + right;
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值