【发布时间】: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