直方圖最大面積

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,310評論 25 708
  • 在此特此聲明:一下所有鏈接均來自互聯網,在此記錄下我的查閱學習歷程,感謝各位原創作者的無私奉獻 ! 技術一點一點積...
    遠航的移動開發歷程閱讀 11,222評論 12 197
  • 這個季節,正是采蕨菜好時候。一場春雨之后,肥嫩的蕨菜肆無忌憚地蹭蹭的往地面鉆。 記得兒時,我與父親經常去后山采...
    我叫魚燕閱讀 657評論 2 0
  • 發酵粉呢
    男性用戶閱讀 262評論 0 0
  • 南城以入冬,寒氣充斥,一入夜,街上行人便以廖廖更何況,現在夜以深了歇。 他在流浪,漂泊在這座城市。在都是陌生人的地...
    公子謹初呀閱讀 337評論 27 10