剑指offer编程题——31 连续子数组的最大和

#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

/*
*   动态规划法 O(n)
*/
int FindMaxSubarr(int *arr, int len){

assert(arr != NULL || len > 0); //假设合法(不合法的话会报错

int maxsum = arr[0];
int cursum = arr[0];

for (int i = 1; i < len; ++i){
//cursum = (cursum + arr[i] > arr[i] ? cursum + arr[i] : arr[i]);
cursum = (cursum > 0 ? cursum + arr[i] : arr[i]); // 更好的写法(相当于将上式简化
maxsum = (maxsum > cursum ? maxsum : cursum);
}
return maxsum;
}


/*
*   穷举法 O(n^2)
*/
vector<int> FindMaxSubarr1(int *arr, int len){  //输出子数组

assert(arr != NULL || len > 0); //假设合法(不合法的话会报错

int maxsum = arr[0];
int a, b;
vector<int> res; //如果先定义res(2),则push_back()后又会增加内存

for (int i = 0; i < len; ++i){  //三重循环  O(n^3)
for (int j = i; j < len; ++j){
int tmp = 0;
for (int k = i; k <= j; ++k)  // k<=j,不然取不到j会遗漏
tmp += arr[k];
if (tmp > maxsum){
maxsum = tmp;
a = i;
b = j;
}
}
}
cout << maxsum<<endl;
for (int i = 0; i < len; ++i){  //二重循环  O(n^2)
int tmp = 0;
for (int j = i; j < len; ++j){
tmp += arr[j];
if (tmp > maxsum){
maxsum = tmp;
a = i;
b = j;
}
}
}
cout << maxsum << endl;
res.push_back(a);
res.push_back(b);
return res;
}


void main31(){

int arr[8] = { -4, 5, 1, -6, 2, 7, -3, 4 };
int len = 8;

//动态规划法
cout << FindMaxSubarr(arr, len) << endl;

//穷举法
vector<int> res = FindMaxSubarr1(arr, len);
auto d1 = res.begin(), d2 = res.end() - 1;
for (int i = *d1; i <= *d2; ++i)
cout << arr[i] << " ";

cout << endl << endl;
}
阅读更多
个人分类: 剑指offer编程
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭