【问题标题】:Given N buildings, find the greatest such solid area formed by consecutive buildings给定 N 个建筑物,找到由连续建筑物组成的最大固体区域
【发布时间】:2023-04-02 04:50:01
【问题描述】:

问题陈述:在某个一维景观中有N栋建筑。每个建筑物的高度由 hi,i∈[1,N] 给出。如果将 K 个相邻的建筑物连接起来,它们将形成一个面积为 K×min(hi,hi+1,…,hi+k−1) 的实心矩形。

给定 N 个建筑物,找出由连续建筑物组成的最大固体区域。

以下是我的解决方案。对我来说看起来不错,但测试用例却失败了。 谁能告诉我以下解决方案有什么问题。

public class Solution {

    public static void main(String[] args) {
        InputReader ir = new InputReader(System.in);
        int N = ir.nextInt();
        long [] hts = new long[N];
        long [] res = new long[N+1];
        for(int i=0; i<N; i++){
            hts[i] = ir.nextLong();            
        }

        //Computes max area for subset of length 1
        long max = Integer.MIN_VALUE;
        for(int i=1; i<=N; i++){
            if(max<hts[i-1]){
                 max = hts[i-1];
            }
        }

        res[1] = max;
        /* Computes max of all the minimum heights 
         * of subsets of length i and 
         * store area at res[i] position
         */
        for(int i=2; i<=N; i++){
            max = Integer.MIN_VALUE;
            for(int j=0; j<N-i+1; j++){
                long min = hts[j];
                for(int k=j+1;k<i-j;k++){
                    if(hts[k]<min){
                        min = hts[k];
                    }
                }
                if(min>max){
                    max = min;
                }                
            }            
            res[i] = i*max;
        }

       // Get maximum area
        long result = res[1];
        for(int i=2; i<N+1;i++){
            if((res[i])>result){
                result = res[i];
            }
        }

        System.out.println(result);
    }
}

【问题讨论】:

    标签: algorithm data-structures stack dynamic-programming


    【解决方案1】:

    方式比蛮力更快的解决方案,只需将每个建筑物映射到它的对应物,如下所示:

               _____
          _____|   |
    ______|<--||-->|_____
    |<---||---||---||-->|
    |    ||   ||   ||   |
    

    现在找到最大面积非常简单:

    int getMaxArea(int[] in)
        map height_to_maxw
    
        stack last_height
        stack at_pos
    
        int max_area = 0
    
        for int i in [0 , length(in))
            if !last_heigth.isEmpty()
                while last_height.peek() > in[i]
                    int l_h = last_height.pop()
                    int l_w = i - at_pos.pop()
    
                    if l_h * l_w > max_area
                        max_area = l_h * l_w
    
        //check if the widest area is the greatest
        int h = min(in[0] , in[length(in) - 1])
        if h * length(in) > max_area
            max_area = h * length(in)
    
        return max_area
    

    【讨论】:

      猜你喜欢
      • 2017-04-24
      • 2021-11-28
      • 2021-11-30
      • 1970-01-01
      • 2019-11-22
      • 2012-04-08
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多