剑指offer-连续子数组的最大和

题目描述

HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)

思路

  • 暴力找出所有的子数组为n(n+1)2n(n+1) \over 2个子数组(数组长度为N),时间复杂度为O(n2)O(n^2);
  • 动态规划法
  • 累加判定法:如果当前累加值<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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章