題目描述
HZ偶爾會拿些專業問題來忽悠那些非計算機專業的同學。今天測試組開完會後,他又發話了:在古老的一維模式識別中,常常需要計算連續子向量的最大和,當向量全爲正數的時候,問題很好解決。但是,如果向量中包含負數,是否應該包含某個負數,並期望旁邊的正數會彌補它呢?例如:{6,-3,-2,7,-15,1,2,2},連續子向量的最大和爲8(從第0個開始,到第3個爲止)。給一個數組,返回它的最大連續子序列的和,你會不會被他忽悠住?(子向量的長度至少是1)
思路
- 暴力找出所有的子數組爲個子數組(數組長度爲N),時間複雜度爲;
- 動態規劃法
- 累加判定法:如果當前累加值<0,那麼對下一個數的累加並沒有提升,所以就捨去,從當前數開始累加。期間判斷最大值即可
AC代碼
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int FindGreatestSumOfSubArray(vector<int> array)
{
if (array.empty())
return 0;
int res = 0x80000000; //-2147483648
int temp = 0;
for (int i = 0; i < array.size(); i++)
{
if (temp > 0)
temp += array[i];
else
temp = array[i];
if (temp > res)
res = temp;
}
return res;
}
};
int main()
{
// vector<int> arr = {6, -3, -2, 7, -15, 1, 2, 2};
vector <int> arr = {-1,-2,-4,-2};
// int test = 0x80000000;
// cout << test << endl;
// cout << 0x80000000 << endl; //unsigned
Solution so;
cout << so.FindGreatestSumOfSubArray(arr) << endl;
return 0;
}
注意問題
// int test = 0x80000000; -2147483648
// cout << test << endl;
// cout << 0x80000000 << endl; //unsigned 2147483648