Container With Most Water

medium Arrays

Problem

The array gives the heights of vertical lines at the positions 0, 1, 2, .... Choose two lines. Together with the x-axis they form a container. The water amount is min(height1, height2) * distance between the lines. Print the largest amount.

Constraints

  • 2 <= n <= 10^5

Examples

Input

9
1 8 6 2 5 4 8 3 7

Output

49

Solutions

Best approachTime O(n)Space O(1)

Checking all pairs costs O(n^2). Starting with the widest pair and moving the shorter line inward loses nothing: with the same short line and a smaller width, the water can only be less.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The largest amount.
 * Approach: Two pointers from the ends.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Start with the widest container: the first and the last line.
        int left = 0;
        int right = a.length - 1;
        long best = 0;

        while (left < right) {
            // Step 2: The water level is the shorter line. The width is the distance.
            long water = (long) Math.min(a[left], a[right]) * (right - left);
            best = Math.max(best, water);

            // Step 3: Move the shorter line inward. Moving the taller line can never give a bigger container.
            if (a[left] < a[right]) {
                left++;
            } else {
                right--;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. Why move the shorter line?