713593. Water the plants

Medium

Water the Plants

Slug: water-the-plants--170646

Difficulty: Medium

Id: 713593

Topic Tags: Greedy, Sorting, Algorithms

Company Tags: Microsoft

Summary

Water the plants is a classic problem in computer science. Given an array of integers representing the heights of the plants and the amount of water that can be carried, determine how many plants can be watered. The key concept involved here is greedy algorithm.

Detailed Explanation

The problem statement says that we have to water the maximum number of plants possible given the available water and plant heights. This problem involves a combination of sorting and greedy algorithms.

To solve this problem, first sort the array in descending order based on the plant heights. Then iterate through the sorted array from left to right. For each pair of adjacent plants, calculate how much water can be carried by considering both plants' heights as the "container" for that amount of water (i.e., the minimum height of the two plants). Keep track of the maximum amount of water that can be carried.

Now, let's write a step-by-step breakdown of the solution:

  1. Initialize an empty array to store the sorted plant heights in descending order.
  2. Iterate through the original array and add each plant's height to the sorted array.
  3. Initialize two pointers (left and right) at the start of the sorted array.
  4. Calculate how much water can be carried by considering both plants' heights as the "container" for that amount of water.
  5. Update the maximum amount of water that can be carried.
  6. If there is still more water available, move the right pointer to the next plant and update the container height.
  7. Finally, return the maximum number of plants that can be watered.

The time complexity for this problem is O(n log n) due to the sorting operation, where n is the total number of plants. The space complexity is O(n), as we need extra space to store the sorted array.

Optimized Solutions

Java

View on GeeksforGeeks
public class WaterPlants {
    public static int waterPlants(int[] heights) {
        int maxWater = 0;
        for (int i = 0; i < heights.length - 1; i++) {
            int leftHeight = heights[i];
            int rightHeight = heights[i + 1];
            int waterAvailable = Math.min(leftHeight, rightHeight);
            maxWater += waterAvailable;
        }
        return maxWater;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.