1. 程式人生 > >CSP201312_3(最大的矩形)(Java100分)

CSP201312_3(最大的矩形)(Java100分)

問題描述
  在橫軸上放了n個相鄰的矩形,每個矩形的寬度是1,而第i(1 ≤ i ≤ n)個矩形的高度是hi。這n個矩形構成了一個直方圖。例如,下圖中六個矩形的高度就分別是3, 1, 6, 5, 2, 3。
題目圖片
  請找出能放在給定直方圖裡面積最大的矩形,它的邊要與座標軸平行。對於上面給出的例子,最大矩形如下圖所示的陰影部分,面積是10。
題目自帶
輸入格式
  第一行包含一個整數n,即矩形的數量(1 ≤ n ≤ 1000)。
  第二行包含n 個整數h1, h2, … , hn,相鄰的數之間由空格分隔。(1 ≤ hi ≤ 10000)。hi是第i個矩形的高度。
輸出格式
  輸出一行,包含一個整數,即給定直方圖內的最大矩形的面積。
樣例輸入


6
3 1 6 5 2 3
樣例輸出
10

下面是Java程式碼:

import java.util.Scanner;
public class MaxRectangle {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int h[]=new int[n];
        int max_height=-1
;//用於儲存輸入資料的最大值。 for(int i=0;i<h.length;i++) { int temp=sc.nextInt(); if(temp>max_height) { max_height=temp; } h[i]=temp; } int length=0; int area=0;//用於儲存結果 for(int i=1;i<=max_height;i++) {//高度從i遍歷到max_height
length=0; int tempLength=0; for(int j=0;j<h.length;j++) { if(h[j]>=i) {//只要高度大於i;則tempLength++ tempLength++; if(j==h.length-1&&tempLength>length) { //這個if語句我當初沒寫,只得了90分。 //至於為什麼往這兒寫,大家自己意會吧。 length=tempLength; } } else { if(tempLength>length) { length=tempLength; } tempLength=0; } } int tempArea=length*i; if(tempArea>area) { area=tempArea; } } System.out.println(area); } }