#include<stdio.h>
#include <malloc.h>
#include <string.h>
#include <string.h>
#include <iostream>
using namespace std;
int MaxSumSub_1(int a[],int n){
//暴力法:算法复杂度为 n^3
int max = 0;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
int sum = 0;
for (int k = i; k <= j; ++k) {
sum += a[k];
}
if(max<sum) max=sum;
}
}
return max;
}
int MaxSumSub_2(int a[],int n){
//暴力法的优化:算法复杂度 n^2
int max = 0;
for (int i = 0; i < n; ++i) {
int sum = 0;
for (int j = i; j < n; ++j) {
sum += a[j];
if(max<sum) max = sum;
}
}
return max;
}
int MAX(int a,int b){
return a>=b? a:b;
}
int MaxSumSub_3(int a[],int n){
//动态规划思想:dp状态转移方程为: max(dp[i]) = max( dp[i-1]+a[i] , a[i]);
//时间复杂度为: n
int max = 0;
int *dp = (int*)malloc(sizeof(int)*(n+1));
memset(dp,0, sizeof(dp));
for (int i = 0; i < n; ++i) {
dp[i+1] = MAX(dp[i]+a[i],a[i]);
if(dp[i+1]>max)
max = dp[i+1];
}
return max;
}
int MaxSumSub_4(int a[],int from,int to){
//当然
//分治法:
if(from==to)
return a[from];
int mid = (from+to)/2;
int m1 = MaxSumSub_4(a,from,mid);
int m2 = MaxSumSub_4(a,mid+1,to);
int left = a[mid],now = a[mid];
for (int i = mid-1; i >= from ; --i) {
now += a[i];
left = MAX(now,left);
}
int right = a[mid+1];
now = a[mid+1];
for (int i = mid+2; i <= to; ++i) {
now += a[i];
right = MAX(now,right);
}
int m3 = left + right;
return MAX(m1,MAX(m2,m3));
}
int main()
{
int n,a[20];
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
cout << MaxSumSub_1(a,n) << endl;
cout << MaxSumSub_2(a,n) << endl;
cout << MaxSumSub_3(a,n) << endl;
cout << MaxSumSub_4(a,0,n) << endl;
return 0;
}
/*
input:
7
1 4 -5 9 8 3 -6
output: (9, 8, 3) 20
8
1 -2 3 10 -4 7 2 -5
output: (3, 10, -4, 7, 2) 18
*/
来源:CSDN
作者:吴成伟
链接:https://blog.csdn.net/qq_43324779/article/details/104118697