11. Topic _ The container that holds the most water

Container that holds the most water

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

Find two of these lines such that, together with the x-axis, they form a container that holds the most water.

Returns the maximum amount of water the container can store.

Instructions: You cannot tilt the container.

public class Solution {
    public int MaxArea(int[] height) {

             int Valume = 0;
            int currentValume = 0;
            int HightVal = 0;//高度Y
            int WidthVal = 0;//宽度X

            int Leftspeen = 0;//左侧的指针
            int Rightspeen = height.Length - 1;//右侧的指针

            bool isChecked = true;//两边是否快要碰头了
            while (isChecked)
            {
                HightVal = height[Leftspeen] > height[Rightspeen] ? height[Rightspeen] : height[Leftspeen];//计算高度
                WidthVal = Rightspeen - Leftspeen;//计算宽度
                currentValume = HightVal * WidthVal;//计算面积
                if (currentValume > Valume)//面积的判断,取得最大值
                {
                    Valume = currentValume;
                }

                if (Leftspeen + 1 == Rightspeen)//是否快要碰头的判断
                {
                    break;
                }

                if (height[Leftspeen] >= height[Rightspeen])//指针的偏移的判断,移动较小的那一侧
                {
                    Rightspeen = Rightspeen - 1;
                }
                else
                {
                    Leftspeen = Leftspeen + 1;
                }
            }
            return Valume;
    }
}

Guess you like

Origin blog.csdn.net/GoodCooking/article/details/130716213