文章出處
文章列表
題目描述
HZ偶爾會拿些專業問題來忽悠那些非計算機專業的同學。今天測試組開完會后,他又發話了:在古老的一維模式識別中,常常需要計算連續子向量的最大和,當向量全為正數的時候,問題很好解決。但是,如果向量中包含負數,是否應該包含某個負數,并期望旁邊的正數會彌補它呢?例如:{6,-3,-2,7,-15,1,2,2},連續子向量的最大和為8(從第0個開始,到第3個為止)。你會不會被他忽悠住?(子向量的長度至少是1)
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
vector<int> B(array.size());
int pre_max = 0;
for(int i=0; i<B.size(); i++){
B[i] = pre_max + array[i];
if(B[i]<0){
pre_max = 0;
}else{
pre_max = B[i];
}
}
int the_max = array[0];
for(int i=1; i<B.size(); i++){
if(B[i]>the_max){
the_max = B[i];
}
}
return the_max;
}
};
文章列表
全站熱搜