0
点赞
收藏
分享

微信扫一扫

[算法]CSDN编程挑战赛之寻找直方图中面积最大的矩形


继续看挑战赛的算法,虽然不指望能得到什么奖项,但能够将自己的思想用程序表达出来就是一种乐趣!

请看题:

[算法]CSDN编程挑战赛之寻找直方图中面积最大的矩形_ios


我的解题思路:

就是判断[i,i+1,i+2...j]之间的最小高度H,然后通过s=(j-i+1)*H来计算面积,然后筛选出最大的面积。

C++代码:

//寻找直方图中面积最大的矩形
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;


//返回一段区间中最矮的那个索引
int short(vector<int> arr,int start,int end)  
{  


int short=arr[start];  
int index=start;  
int i;  
if(start==end)  
{  
return index;   
}  




for(i=start;i<=end;i++)  
{     
if(short>=arr[i])  
{  
short=arr[i];  
index=i;  
}  
}  
return index;  
}


int largestRectangleArea(vector<int> &height) {
int area = 0;
int max = 0;
int height_index=0;
for (int i=0;i<height.size();i++)
{
for (int j=i;j<height.size();j++)
{
height_index=shortest(height,i,j);  
area=(j-i+1)*(height[height_index]);  
if(max < area)  
max=area;  
}
}
return max;
}








C++具有模板还稍微好一点,如果用C写可以用指针来写


C语言代码:

#include <stdio.h>

//找出区间最小值的索引
int shortindex(const int * height,int begin,int end)
{
	int shortindex;
	int shortheight=*height;
	if (begin=end)
	{
		return begin;
	}
	else
	{
		for (int i=begin;i<end;i++,height++)
		{
			if (shortheight>*height)
			{
				shortheight=*height;
				shortindex=i;
			}
		}
		return shortindex;
	}
	
}

//数组指针,数组个数
int largestRectangleArea(const int *height,int n)
{
	int area = 0;
	int max = 0;
	int height_index = 0;
	for (int i=0;i<n;i++)
	{
		for (int j=i;j<n;j++)
		{
			height_index=shortindex(height,i,j);
			area = (j-i+1)*(height[height_index]);
			if (max<area)
			{
				max=area;
			}
		}
	}
	return max;
}



举报

相关推荐

0 条评论