1.10-Greedy algorithm related exercises

Topic (the container that holds the most water)

oj link: https://leetcode.cn/problems/container-with-most-water/submissions/394381059/

Given an  n integer array  of length height . There is  n a vertical line,  i the two endpoints of the first line are  (i, 0) and  (i, height[i]) .

Find two of these lines so that  x the container they form together with the axis can hold the maximum amount of water.

Returns the maximum amount of water the container can store.

Explanation: You cannot tilt the container

example

1.
Input: [1,8,6,2,5,4,8,3,7]
 Output: 49 
 Explanation: The vertical line in the figure represents the input array [1,8,6,2,5,4,8,3, 7]. In this case, the maximum amount of water the container can hold (shown in blue) is 49.

2.
Input: height = [1,1]
 Output: 1

hint

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

train of thought

This question requires the formation of the largest area, then we can set the left and right pointers, move from the left and right sides to the middle, move the end with less water each time, calculate the area produced each time, and record the maximum value, each calculation After updating the maximum value, the final output of max is over.

the code

class Solution {
    public int maxArea(int[] height) {
        int right = height.length - 1;
        int left = 0;
        int max = 0;

        while (left <right) {
            int sq = (right - left)*Math.min(height[right], height[left]) ;
            max = Math.max(max, sq);
            if(height[left] <= height[right] ) {
                left++;
            }else {
                right--;
            }
        }
        return max;
    }
}

Guess you like

Origin blog.csdn.net/m0_63975371/article/details/128637875