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

}

你可能感兴趣的:(idea)