702902. Water Collection

Medium

Water Collection

Slug: amount-of-water1348

Difficulty: Medium

Id: 702902

Topic Tags: Arrays, Data Structures

Company Tags: Amazon, Adobe

Summary

The problem is about collecting water in a row of buckets. You are given an array of non-negative integers representing the height of each bucket at different positions. The goal is to find the maximum amount of water that can be collected between two adjacent buckets.

This problem involves arrays and data structures, with a focus on optimization and dynamic programming.

Detailed Explanation

The approach to this problem is to iterate through the array from both ends (left and right) and keep track of the maximum height of the buckets at each position. The maximum amount of water that can be collected between two adjacent buckets is the minimum of the heights of the two buckets multiplied by the distance between them.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, left and right, to the start and end of the array respectively.
  2. Initialize max_water to 0.
  3. Iterate through the array from both ends:
    • For each pair of buckets at positions left and right, calculate the maximum amount of water that can be collected between them: min(height[left], height[right]) * (right - left).
    • Update max_water if the calculated value is greater than the current maximum.
  4. Return max_water.

Here's an ASCII art diagram to illustrate the process:

  +--------+--------+--------+--------+
  |        |        |        |        |
  |  1    | 2     | 3      | 4       |
  |        |        |        |        |
  +--------+--------+--------+--------+

  left (start) -> 1
  right (end) -> 4

  Calculate max_water for each pair:
  (min(1, 2) * (2 - 1)) = 1
  (min(2, 3) * (3 - 2)) = 2
  ...

The time complexity of this solution is O(n), where n is the length of the array. The space complexity is O(1), as we only use a few extra variables to store the pointers and maximum water.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxWater(int[] height) {
    int max_water = 0;
    int left = 0, right = height.length - 1;
    while (left < right) {
        int water = Math.min(height[left], height[right]) * (right - left);
        max_water = Math.max(max_water, water);
        if (height[left] <= height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return max_water;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.