[科技部与你共成长] 两道题

第一道:据说是google面试题
有N个整数,求其中任意N-1个数的乘积中的最大值。
例如-4,-1,2的最大值就是4;
最好给出复杂度分析。这道题我没有找到标准答案,大家可以把自己的想法贴出来讨论一下。
第二道:编程练习题 POJ1163
                                              The Triangle
                                                      7
                                                   3   8
                                                 8   1   0
                                               2   7   4   4
                                             4   5   2   6   5
The above figure shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right. 
上图显示了一个数字三角,请编写程序计算从顶点到最底层的一条路径能得到的最大和。
每次路径从顶点出发只能向下面相邻的左节点或右节点前进。比如上图的最大路径就是7-3-8-7-5.

 

----------------------------------------------------------------------------------------------

答案:

第一道,我的思路是,首先声明变量,整形的z=0,n=负无穷,p=正无穷,sum=1,然后遍历一遍,遍历的过程中作如下工作
:依次读入每一个数,
如果不是0,则乘到sum上,并且如果是负数同时又比n大的话,则更新n为这个值;如果是正数又比p小的话,将p更新为这个值
如果是0,则不乘到sum上,并且z++;//z记录数列中0的个数,当z大于1时整个程序跳出,返回最大可能值0
遍历完之后,如果z=1,并且sum为负数,则返回0;如果z=1并且sum为正数,则返回sum
如果z=0并且sum为负数,则返回sum/n,如果z=0并且sum为正数则返回sum/p;
复杂度的话,遍历一遍为n,要做o(n)次乘法,每次比较的复杂度为2n,最后的复杂度为O(n);
第二道题:
贴一下我的代码,仅供参考,可以AC
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n;cin>>n;
int total=(1+n)*n/2,*num=new int[total] ;
for(int i=0;i<total;i++)
cin>>num[i];
for(int i=total-1;i>0;i--)//从最后一个数算起
{
int line=sqrt(i*2+0.25)-0.5;//计算当前在第几行
if(i!=(1+line)*line/2)
num[i-line-1]=num[i-line-1]+(num[i]>num[i-1]?num[i]:num[i-1]);//迭代更新当前数所在的小三角内的顶点值
}
cout<<num[0]<<endl;//更新到最后顶点处保存的就是最大的和
return 0;
}

posted @ 2011-01-03 23:26  华工微软俱乐部科技部  阅读(176)  评论(0编辑  收藏  举报