金山(Kingsoft)服务器端开发工程师笔试题和面试题答案(2)

招聘笔试题2018-11-22李一老师

  问题补充:这种算法的时间复杂度是O(n^2) ,效率太低了,在网友张立志同学的提示下,我用动态规划算法对程序做了优化。时间复杂度是O(n)。代码如下。

  #include int main() { int num[]={5,-1,1,-10,5,-1,5,-20,1,-1,3}; int n=sizeof(num)/sizeof(int); int sum=0; int max=num[0];// record the value of max part int start=0;// the start position of the max part int end=0;// the end position of the max part int temp_start; for(int i=0;i { sum+=num[i]; // update max part if(max { max=sum; end=i; start=temp_start; } // find new max part if(sum<0) { sum=0; temp_start=i+1; } } printf("max=%d/n",max); printf("start=%d/n",start); printf("end=%d/n",end); return 0; } #include int main() { int num[]={5,-1,1,-10,5,-1,5,-20,1,-1,3}; int n=sizeof(num)/sizeof(int); int sum=0; int max=num[0];// record the value of max part int start=0;// the start position of the max part int end=0;// the end position of the max part int temp_start; for(int i=0;i { sum+=num[i]; // update max part if(max { max=sum; end=i; start=temp_start; } // find new max part if(sum<0) { sum=0; temp_start=i+1; } } printf("max=%d/n",max); printf("start=%d/n",start); printf("end=%d/n",end); return 0; }

相关推荐

猜你喜欢

大家正在看

换一换