`
yiyidog125
  • 浏览: 13198 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

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
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics