Розбір
First, compute the volume of water in the container formed by the outermost vertical lines, i.e., between the lines of the pair . Then, move the pointers and towards each other:
if , increase by ;
if , decrease by ;
The volume of water between the lines and is equal to . Among all the calculated values, find the maximum.
The problem can be solved in . However, due to the constraint , such a solution would result in a time limit exceeded (TLE). It is sufficient to iterate over the pairs of lines , where , and for each such pair, calculate the volume of water they can hold. Among all the computed values, find the maximum volume.
Example
The container from the first test looks like this:
The maximum amount of water can be held between the lines and . The water level height is , and the volume of water is .
Algorithm realization
Read the input data.
scanf("%d", &n); h.resize(n); for (i = 0; i < n; i++) scanf("%lld", &h[i]);
Store the maximum amount of water the container can hold in the variable .
long long res = 0;
Initialize two pointers .
int l = 0, r = h.size() - 1;
Move the pointers and towards each other until they meet.
while (l < r) {
The volume of water between the lines and is equal to . Among all such volumes, find the maximum.
res = max(res, min(h[l], h[r]) * (r - l));
Move the pointers.
if (h[l] < h[r]) l += 1; else r -= 1; }
Print the answer.
printf("%lld\n", res);
Algorithm realization – O(n^2), Time Limit
Read the input data.
scanf("%d", &n); v.resize(n); for (i = 0; i < n; i++) scanf("%lld", &v[i]);
Store the maximum amount of water the container can hold in the variable .
long long res = 0;
Iterate over all possible pairs of lines , where .
for (i = 0; i < n; i++) for (j = i + 1; j < n; j++)
The volume of water between the lines and is equal to . Among all such volumes, find the maximum.
res = max(res, min(v[i], v[j]) * (j - i));
Print the answer.
printf("%lld\n", res);