您的位置:首页 > 编程语言

编程珠玑的一道令我surprise的题目,竟然和Google的笔试题一样。

2010-12-16 10:36 483 查看
其实题目很简单,就是计算一个整数数组中,连续的最大子数组。

一开始想到肯定是个O(n*n)的算法:maxSectionGood
后来使用递归O(n*log(n)):maxSectionExcellent
最经典的是最后一个算法,提升到了O(n):maxSectionPrefect

Google 笔试题:

input: an array of int which represent a binary number the bit is 1

output: the count of 1 triple of the number

input: an array of int

output: the max sum of continual element of the array of input

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
int maxThree(int a,int b, int c)
{
if ((a>=b)&&(a>=c))
return 0;
if ((b>=1)&&(b>=c))
return 1;
if ((c>=b)&&(c>=a))
return 2;
}
int maxSectionGood(vector<int> inArray)
{
int max = inArray[0];
for(unsigned int i=0;i<inArray.size();i++)
{
int sum = 0;
for(unsigned int j=i;j<inArray.size();j++)
{
sum = sum + inArray[j];
if (sum>max)
{
max = sum;
}
}
}
return max;
}
int maxSectionExcellent(vector<int> inArray, int& startIndex)
{
if (inArray.size()>1)
{
int t = inArray[inArray.size()-1];
inArray.pop_back();
int fromIndex = 0;
int maxsofar = maxSectionEnhanced(inArray,fromIndex);
int sum = t;
int tempmax = t;
for (int i=inArray.size()-1; i>=fromIndex; i--)
{
sum=sum+inArray[i];
if (sum>tempmax)
{
tempmax = sum;
startIndex = i;
}
}
int maxThreeR = maxThree(t,sum,maxsofar);
if (maxThreeR==0)
{
startIndex = inArray.size();
return t;
}
if (maxThreeR==1)
{
startIndex = fromIndex;
return sum;
}
if (maxThreeR==2)
{
startIndex = fromIndex;
return maxsofar;
}
}else
{
startIndex = 0;
return inArray[0];
}
}
int max(int a,int b)
{
if (a>b)
return a;
else
return b;
}
int maxSectionPrefect(vector<int> inArray)
{
int maxsofar = 0;
int masendinghere=0;
for (int i=0;i<inArray.size();i++){
masendinghere = max(masendinghere+inArray[i],0);
maxsofar = max(maxsofar,masendinghere);
cout<<"masendinghere:"<<masendinghere<<" maxsofar:"<<maxsofar<<endl;
}
if( masendinghere>maxsofar)
return masendinghere;
else
return maxsofar;
}
/*
int main() {
vector<int> t;
t.push_back(31);
t.push_back(-41);
t.push_back(59);
t.push_back(26);
t.push_back(-53);
t.push_back(58);
t.push_back(97);
t.push_back(-93);
t.push_back(-23);
t.push_back(84);
int start=0;
int result = maxSectionPrefect(t);
//int result = maxSectionExcellent(t,start);
//int result = maxSectionGood(t);
cout << "Result: " << result << endl; // prints !!!Hello World!!!
return 0;
};
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: