When pairing two heights, the volume is determined by the minimum height.
Then, we focus here on the determination of the min height of this pair.
For each index i
, corresponding to a height A[i]
, we determine the minimum and the maximum indices corresponding
to all A
values greater than A[i]
.
For that, we sort the indices i = index[.]
according to the values A[i]
.
For a given i = index[j]
, all canditate indices correspond to the index[k]
, for k > i
.
A simple loop allow to find the minimum and maximum values of these index[k]
.
The complexity is dominated by the sorting: O(nlogn)
Here is a code in C++, rather simple and easy to understand whatever the language you are using.
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int max_vol (const std::vector<int> &A) {
int vmax = 0;
int n = A.size();
std::vector<int> index(n);
std::iota (index.begin(), index.end(), 0);
auto comp = [&] (int i, int j) {return A[i] < A[j];};
std::sort (index.begin(), index.end(), comp);
int index_max = index[n-1];
int index_min = index[n-1];
for (int i = n-2; i >= 0; --i) {
int d0 = std::abs (index[i] - index_max);
int d1 = std::abs (index[i] - index_min);
int vol = std::max (d0, d1) * A[index[i]];
if (vol > vmax) vmax = vol;
index_max = std::max(index[i], index_max);
index_min = std::min(index[i], index_min);
}
return vmax;
}
int main() {
std::vector<int> heights = {2, 9, 6, 3, 5, 7};
auto max_volume = max_vol (heights);
std::cout << "max volume = " << max_volume << std::endl;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…