Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use C # to realize the container that holds the most water

Shulou Source: shulou.com Published: 2022-06-01 20:50:14 09月14日 Update

This article introduces the relevant knowledge of "how to use C# to achieve the container that holds the most water". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The container that holds the most water

Difficulty: medium

I will give you n non-negative integers, a _ 1, a _ 2, and a _ 1, where each number represents a point in coordinates (I, ai). Draw n vertical lines in the coordinates. The two endpoints of the vertical line I are (I, ai) and (I, 0), respectively. Find two of the lines so that the container composed of them and the x-axis can hold the most water.

Note: you cannot tilt the container, and the value of n is at least 2.

The vertical line in the picture represents the input array [1, 8, 6, 2, 5, 5, 4, 8, 3, 7]. In this case, the maximum value that the container can hold water (represented as the blue part) is 49.

Example:

Input: [1, 8, 6, 2, 5, 4, 8, 3, 7]

Output: 49

Answer to the question:

The first solution: violence

Public int MaxArea (int [] height) {/ / solution 1: int res = 0; for (int I = 0; I

< height.Length; i++) { for (int j = i + 1; j < height.Length; j++) { int thisArea = (j - i) * Math.Min(height[i], height[j]); res = Math.Max(res, thisArea); } } return res; } 第二种解法:双指针(左指针大于右指针,left++) public int MaxArea(int[] height) { int res = 0; int left = 0; int right = height.Length - 1; while (left < right) { int thisArea = (right - left) * Math.Min(height[left], height[right]); res = Math.Max(res, thisArea); if (height[left] >

Height [right]) right--; else left++;} return res;}

The third solution: double pointer optimization (left pointer less than or equal to minimum height, left++)

Public int MaxArea (int [] height) {int res = 0; int left = 0; int right = height.Length-1; while (left < right) {int minHeight = Math.Min (height [left], height [right]); int thisArea = (right-left) * minHeight; res = Math.Max (res, thisArea); if (left < right & & height [left])

Tags: Containers pointers solutions multi-water vertical lines Centers representatives content coordinates more knowledge input output practical maximum minimum successful learning and then two interior painting Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information macOS Xiaomi Docker MySQL