您的位置:首页 > 职场人生

面试题35:连续子数组的最大和

2015-12-30 20:05 393 查看
题目:

输入一个整型数组,数组里有正数也有负数。数组中一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。

边界条件及异常:

空数组。

思路:

考虑数组2,1,-4,3,4,5,-7

我们用数组DP来存子数组包括自己和自己前面元素的最大的和,则有:

DP[]={2,3,-1,3,7,12,5}

不难得出所有子数组最大的和是12。

时间复杂度:O(n)

空间复杂度:O(n)

哈哈,相信已经看出来为什么取名为DP了,因为是动态规划的思想。

我们可以进行优化,只需存储当前最大值和前一个元素对应的最大值。

这样空间复杂度为O(1)。

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <stack>
#include <algorithm>
#include <hash_set>  //for hashtable
#include <hash_map>
#include <set>
#include <ctime>
using namespace std;

int maxSumOfSubArray(vector<int> nums)
{
int size = nums.size();
if (size == 0) return 0;
int max = nums[0];
int preMax = nums[0];
for (int i = 1; i < size; ++i)
{
int curMax = (preMax + nums[i]) > nums[i] ? (preMax + nums[i]) : nums[i];
if (curMax > max) max = curMax;
preMax = curMax;
}
return max;
}

int main()
{
int arr[] = { 8, -7, 9,-8, 5, 4, 1, 2, -3 };
vector<int> nums(arr, arr + 9);
cout << maxSumOfSubArray(nums) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: