欢迎访问我的CCF认证解题目录
题目描述
思路过程
直接暴力解法,两层for循环,第一层表示以第i个为结尾,第二层表示第j个连接到第i个,每次取j-i中的最小值乘以j-i的长度,如果比maxSum大,则更新maxSum。
如上面的例子
第一层:3
第二层:1,2(2*1)
第三层:6,2,3
第四层:5,10,3,4
...
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int maxSum = 0;//记录当前最大和
int[] height = new int[n];//存储高度
for ( int i = 0; i < n; i++ ) height[i] = in.nextInt();//输入
for ( int i = 0; i < height.length; i++ ) {//以i结尾
int min = Integer.MAX_VALUE;
for ( int j = i; j >= 0; j-- ) {//向前遍历
min = Math.min(height[j], min);//找出高度最小的
maxSum = Math.max(maxSum, min*(i-j+1));
}
}
System.out.println(maxSum);
}
}
LeetCode官方题解
链接:官方题解
思路请观看官方题解
分治法:时间复杂度O(),最坏为
public static int largestRectangleArea(int[] heights) {
if ( heights == null || heights.length == 0 ) return 0;
return maxArea(heights, 0, heights.length-1);
}
public static int maxArea( int[] heights, int left, int right ) {
int index = left, max = 0;
if ( left <= right ) {
for ( int i = left+1; i <= right; i++ ) {//找出下标最小的
index = heights[i] < heights[index] ? i:index;
}
max = Math.max(max, heights[index]*(right-left+1));//以该点为最高点
int leftMax = maxArea(heights, left, index-1);//分治
int rightMax = maxArea(heights, index+1, right);
max = Math.max(max, Math.max(leftMax, rightMax));
}
return max;
}
栈:时间复杂度O(n)
public static int largestRectangleArea(int[] heights) {
int max = 0;
ArrayList<Integer> stack = new ArrayList<Integer>();
stack.add(-1);
for ( int i = 0; i < heights.length; i++ ) {
//开始下降
while ( stack.size() > 1 && heights[stack.get(stack.size()-1)] > heights[i] ) {
//所有高度为升序,所以长度为i-stack.get(stack.size()-2)-1------当前位置-1到上上个位置
max = Math.max(max, (i-stack.get(stack.size()-2)-1)*heights[stack.get(stack.size()-1)]);
stack.remove(stack.size()-1);
}
stack.add(i);
}
while ( stack.size() > 1 ) {
max = Math.max(max, (heights.length-stack.get(stack.size()-2)-1)*heights[stack.get(stack.size()-1)]);
stack.remove(stack.size()-1);
}
return max;
}