原题网址:http://www.lintcode.com/zh-cn/problem/maximum-subarray/
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3]
,符合要求的子数组为[4,−1,2,1]
,其最大和为6
标签
1 #include <iostream>
2 #include <vector>
3 #include <math.h>
4 using namespace std;
5
6
7 int maxSubArray(vector<int> &nums) //找整形数组的最大子数组;
8 {
9 int size=nums.size();
10 int maxsum=nums[0];
11
12 for (int i=0;i<size;i++)
13 {
14 int tempsum=0;
15 for (int j=i;j<size;j++)
16 {
17 tempsum=tempsum+nums[j];
18 if (tempsum>maxsum)
19 {
20 maxsum=tempsum;
21 }
22 }
23 }
24 return maxsum;
25
26
27
42 }
贪心法,时间复杂度O(n)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
int maxSubArray(vector<int> &nums) {
// write your code here
int size = nums.size();
int max = nums[0];
int nowm = 0;
for (int i = 0; i < size; i++)
{
nowm += nums[i];
if (nowm > max) {
max = nowm;
}
if (nowm < 0) {
nowm = 0;
}
}
return max;
}
};
参考网址:
1、https://blog.csdn.net/sinat_30440627/article/details/54924737
2、https://blog.csdn.net/linglian0522/article/details/70670801