根据样例我们发现,只要找到最大和次大的。然后答案就是次大的 * (n - 1)即可
import java.util.Scanner;
public class MaxRainwater {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入
int n = scanner.nextInt();
long[] heights = new long[n];
for (int i = 0; i < n; i++) {
heights[i] = scanner.nextLong(); // 使用 long 类型
}
// 计算接水量
System.out.println(maxRainwater(n, heights));
}
public static long maxRainwater(int n, long[] heights) {
// 找到最高和第二高的木板
long max1 = Long.MIN_VALUE;
long max2 = Long.MIN_VALUE;
for (long height : heights) {
if (height > max1) {
max2 = max1;
max1 = height;
} else if (height > max2) {
max2 = height;
}
}
// 计算可以接的雨水总量
return max2 * (n - 1);
}
}
def max_rainwater(n, heights):
# 找到最高和第二高的木板
max1 = max(heights)
heights.remove(max1) # 移除最高木板后再找第二高
max2 = max(heights)
# 计算可以接的雨水总量
rainwater = max2 * (n - 1)
return rainwater
# 读取输入
n = int(input())
heights = list(map(int, input().split()))
# 输出结果
print(max_rainwater(n, heights))
#include <bits/stdc++.h>
using namespace std;
long long maxRainwater(int n, vector<long long>& heights) {
// 找到最高和第二高的木板
long long max1 = LLONG_MIN, max2 = LLONG_MIN;
for (long long height : heights) {
if (height > max1) {
max2 = max1;
max1 = height;
} else if (height > max2) {
max2 = height;
}
}
// 计算可以接的雨水总量
return max2 * (n - 1);
}
int main() {
int n;
cin >> n;
vector<long long> heights(n); // 使用 long long 类型
for (int i = 0; i < n; i++) {
cin >> heights[i];
}
// 输出结果
cout << maxRainwater(n, heights) << endl;
return 0;
}
OJ会员可以通过点击题目上方《已通过》查看其他通过代码来学习。
小红有n个插在数轴上的木板,其中第i块木板高度为a,相邻木板之间的宽度为1,木板本身的宽度忽略不计。 现在小红要使用这n个木板来接雨水,他想知道如果他可以提前调整这些木板的排列顺序,那么最多可以接多少雨水?
第一行输入一个整数 n(2≤n≤2×105)代表数组中的元素数量。
第二行输入n个整数a1,a2,...,an(1≤ai≤109)表示每块木板的高度。
在一行上输出一个整数,代表在任意排列所有木板后,可以接到雨水的最大量。
输入
4
1 3 4 5
输出
12
