当前位置:网站首页>Composition maximum area

Composition maximum area

2022-06-09 12:05:00 N. LAWLIET

problem
ask : give n Nonnegative integers , Each integer represents a coordinate point (i,ai) Draw n Bar vertical line , Line i There are two endpoints (i,ai) and (i,0) Their starting points are contained in x On the shaft , Excuse me, n How can a line contain the most water .( Select any two poles to store the most water )

Example
A little

thought
Find the maximum area between two rods , Double pointer method . Find the maximum area , Minimum value of height selector lever .

Code

public class Code02_ContainerWithMostWater {
    
	
	public static int  maxArea(int[] h) {
    
		int r = h.length;
		int l  =0;
		int max = 0;
		while(l<r) {
    
			max = Math.max(max, Math.min(h[l], h[r])*(r-l));
			if(h[l]<h[r]) l++;
			else {
    
				r--;
			}
		}
		return max;
	}

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		int N = Integer.parseInt(scanner.nextLine());
		int[] h = new int[N];
		for(int i = 0;i<N ;i++) {
    
			h[i] = scanner.nextInt();
		}
		int res = maxArea(h);
		System.out.println(res);

	}

}

原网站

版权声明
本文为[N. LAWLIET]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091123562447.html