1. 程式人生 > >演算法——Largest Rectangular Area in a HistogramLargest Rectangular Area in a Histogram

演算法——Largest Rectangular Area in a HistogramLargest Rectangular Area in a Histogram

題目:給定的直方圖中查詢最大的矩形。假設每個資料的的寬度都為1,高度不同。例如:使用[6, 2, 5, 4, 5, 2,6],來表示 7個直返圖,圖中最大的矩形面積是12。這裡寫圖片描述
思路一:
對每個給定的資料的每個點按照順序的左右各算一遍,最後對比每個點的最大值。

python程式碼:

class Solution:
    # @param height, a list of integer
    # @return an integer
    def largestRectangleArea(self, height):
        n = len(height)

        # left[i], right[i] represent how many bars are >= than the current bar
left = [1] * n right = [1] * n max_rect = 0 # calculate left #從左往右計算每個點左側大於該點的數量總和 for i in range(0, n): j = i - 1 while j >= 0: if height[j] >= height[i]: left[i] += left[j] #注意這裡有個跳躍,應為是從左往右之間的每一個letf[]點都儲存著比它大的點數量,所以要跳過這些位置。
j -= left[j] else: break # calculate right for i in range(n - 1, -1, -1): j = i + 1 while j < n: if height[j] >= height[i]: right[i] += right[j] #同上 j += right[j] else
: break #最後的計算每個點的最大值 for i in range(0, n): max_rect = max(max_rect, height[i] * (left[i] + right[i] - 1)) #計算的點在左右都算了一次,所以減去1 return max_rect

思路二:
通過棧來做,主要思想就是求兩個值,對於一個值‘x’需要找的他兩側第一個小於‘x’的位置,就可以計算出當該值被作為標準計算的矩形的寬。

  1. 構造一個棧
  2. 將資料儲存到陣列height[]
  3. 對每個值判斷如果棧為空或者或者大於棧頂的值就可以加入棧
  4. 一旦小於的棧頂值就找到棧頂值的左右兩個小值點,將棧頂彈出的計算以該值為標準的矩形。寬為兩個最小點中間的距離,對比最大值就可以得到答案。

    java程式碼:

public class Solution {
    public int largestRectangleArea(int[] height) {
        int len = height.length;
        Stack<Integer> s = new Stack<Integer>();
        int maxArea = 0;
        for(int i = 0; i <= len; i++){
            int h = (i == len ? 0 : height[i]);
            if(s.isEmpty() || h >= height[s.peek()]){
                s.push(i);
            }else{
                int tp = s.pop();
                maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
                i--;
            }
        }
        return maxArea;
    }
}

相關推薦

演算法——Largest Rectangular Area in a HistogramLargest Rectangular Area in a Histogram

題目:給定的直方圖中查詢最大的矩形。假設每個資料的的寬度都為1,高度不同。例如:使用[6, 2, 5, 4, 5, 2,6],來表示 7個直返圖,圖中最大的矩形面積是12。 思路一: 對每個給定的資料的每個點按照順序的左右各算一遍,最後對比每個點的最大值。

【LeetCode-面試演算法經典-Java實現】【151-Reverse Words in a String(反轉字串中的單詞)】

原題   Given an input string, reverse the string word by word.   For example,   Given s = "the sky is blue",   return "bl

[TS] Implement a singly linked list in TypeScript

master content pointer lis github deque struct scrip mov In a singly linked list each node in the list stores the contents of the node an

【轉】How to initialize a two-dimensional array in Python?

use obj class amp example list tty address add 【wrong way:】 m=[[element] * numcols] * numrowsfor example: >>> m=[[‘a‘] *3] * 2&g

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

mina term spa attempted user create style pre temp 啟動mongodb遇到的一個問題和解決: 轉(http://blog.csdn.net/u012877472/article/details/51001025) Mongo

A cycle was detected in the build path of project

java在ecilpse 的 控制臺 旁邊 的problems 旁邊 出現 A cycle was detected in the build path of project ...解決Eclipse中Java工程間循環引用而報錯的問題 如果我們的項目包含多個工程(project),而它們之間又是循環引用的關

[React] Reference a node using createRef() in React 16.3

lin node eat can lesson return using field div In this lesson, we look at where we came from with refs in React. Starting with the deprec

xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH

view chmod baidu aid log nts pac mod ica Xcode升級到8.3後 用命令進行打包 提示下面這個錯誤 xcrun: error: unable to find utility "PackageApplication", not a

A cycle was detected in the build path of project項目相互依賴

pre lips war 報錯 ces bsp clip cli ble 解決Eclipse中Java工程間循環引用而報錯的問題 如果我們的項目包含多個工程(project),而它們之間又是循環引用的關系,那麽Eclipse在編譯時會拋出如下一個錯誤信息: “A cycle

How to setup a slave for replication in 6 simple steps with Percona XtraBackup

second path binlog ica direct isam fetch owin value Data is, by far, the most valuable part of a system. Having a backup done systema

[WASM + Rust] Debug a WebAssembly Module Written in Rust using console.log

Having some kind of debugging tool in our belt is extremely useful before writing a lot of code. In this lesson we build a println!()-style syntax u

SDPA: Toward a Stateful Data Plane in Software-Defined Networking

文章名稱:SDPA: Toward a Stateful Data Plane in Software-Defined Networking 發表時間:2017 期刊來源:IEEE/ACM Transactions on Networking 摘要 OpenFlow僅僅提供簡單的“mat

[vscode react-native] xcrun: error: unable to find utility "instruments", not a developer tool or in

執行環境:Mac + vscode + xcode IOS ReactNative執行的時候出現這個錯誤 使用vscode執行reactnative 專案時報錯:xcrun: error: unable to find utility "instruments", not a develop

[Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript

In this lesson we are going to setup a project from scratch by introducing the JavaScript snippet to load a WebAssembly module. We demonstrate two differen

藍書(演算法競賽進階指南)刷題記錄——POJ3468 A Simple Problem with Intergers(樹狀陣列維護差分)

題目:poj3468. 題目大意:給定一個序列a,要求支援: 1.格式C a b c,表示將[a,b]的權值都加上c. 2.格式Q a b,表示查詢[a,b]的權值和. 線段樹裸題(我像個傻子一樣寫了個LCT做了一遍),可是我們這裡不用線段樹,我們討論樹狀陣列的解法. 我們已

collatz number,迴文數,love,map函式,漢若塔,佛祖鎮樓,read a word by random in 5s,the star of sand glass

1 collatz number def collatz(num): '''collatz number ''' if num % 2 == 0: n = num / 2 return n elif num % 2 == 1:

delete specific lines in a set of files in a folder

import os myinst = ['foo','bar'] def wipe_lines(folder): for (dirpath, dirnames, filenames) in os.walk('/Users/faramir/git/'+ folder):

QObject: Cannot create children for a parent that is in a different thread.

QObject: Cannot create children for a parent that is in a different thread. (Parent is QNetworkAccessManager(0x17d16c88), parent's thread is QThre

演算法42--Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given targetvalue. Your algorit

How do I add a Foreign Key Field to a ModelForm in Django?

What I would like to do is to display a single form that lets the user: Enter a document title (from Document model