直方图最大面积

Q:给定一个直方图,这里盗一下图,http://blog.csdn.net/nisxiya/article/details/46562951
例如

20150619153844882.jpg

的最大面积为10
烦烦烦.jpg

A:关键在于单调栈的运用,单调栈可以找到每个元素左右两边离他最近的比他小(或者大)的数。

import java.util.*;
import java.io.*;
public class 最大直方图面积 {

    public static void main(String[] args) throws Exception{
        Scanner scanner=new Scanner(System.in);
        int length = scanner.nextInt();
        int[] arr = new int[length];
        for (int i = 0; i < length; i++) {
            arr[i] = scanner.nextInt();
        }
        long maxArea = getMaxArea(arr);
        System.out.println(maxArea);
    }
    public static long getMaxArea(int[] arr) {
        long max = 0;
        int[] temp = new int[arr.length];
        Stack<Integer> stack = new Stack<>();
        int preIndex;
        for (int i = 0; i < arr.length; i++) {
            while (!stack.isEmpty() && (arr[i] < arr[stack.peek()])) {
                preIndex = stack.pop();
                if(stack.isEmpty()){
                    temp[preIndex] = i -preIndex;
                }else{
                    temp[preIndex] = i - stack.peek()-1;
                }
            }
            stack.push(i);
        }
        int end=arr.length-1;
        while(!stack.isEmpty()){
            preIndex = stack.pop();
            if(stack.isEmpty()){
                temp[preIndex] = 1;
            }else{
                temp[preIndex] = end - stack.peek();
            }
        }
        for (int i = 0; i < arr.length; i++) {
            max = Math.max(max, arr[i] * temp[i]);
        }
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,536评论 25 708
  • 在此特此声明:一下所有链接均来自互联网,在此记录下我的查阅学习历程,感谢各位原创作者的无私奉献 ! 技术一点一点积...
    远航的移动开发历程阅读 11,239评论 12 197
  • 这个季节,正是采蕨菜好时候。一场春雨之后,肥嫩的蕨菜肆无忌惮地蹭蹭的往地面钻。 记得儿时,我与父亲经常去后山采...
    我叫鱼燕阅读 658评论 2 0
  • 发酵粉呢
    男性用户阅读 262评论 0 0
  • 南城以入冬,寒气充斥,一入夜,街上行人便以廖廖更何况,现在夜以深了歇。 他在流浪,漂泊在这座城市。在都是陌生人的地...
    公子谨初呀阅读 337评论 27 10