最大子串行和的演算法分析

2021-08-04 21:39:52 字數 1727 閱讀 9982

// maxsubsequencesum.cpp : 定義控制台應用程式的入口點。

// 求陣列的最大連續子串行和

// 2017/8/3

#include "stdafx.h"

int maxsubsequencesum1(int a, int n);

int maxsubsequencesum2(int a, int n);

int maxsubsequencesum3(int a, int n);

static

int maxsubsum(int a, int, int);

int maxsubsequencesum4(int a, int n);

int main()

; printf("alg1:%d\n", maxsubsequencesum1(a, 6));

printf("alg2:%d\n", maxsubsequencesum2(a, 6));

printf("alg3:%d\n", maxsubsequencesum3(a, 6));

printf("alg4:%d\n", maxsubsequencesum4(a, 6));

return0;}

//演算法1:時間複雜度o(n3)

int maxsubsequencesum1(int a,int n)

if (thissum>maxsum)}}

return maxsum;

}//演算法2:時間複雜度o(n2)

int maxsubsequencesum2(int a, int n) }}

return maxsum;

}//演算法3:時間複雜度為o(nlogn)

int maxsubsequencesum3(int a, int n)

static

int maxsubsum(int a, int left, int right)

else

}center = (left + right) / 2;

maxleftsum = maxsubsum(a, left, center);

maxrightsum = maxsubsum(a, center + 1, right);

maxleftbordersum = 0;

leftbordersum = 0;

for ( i = center; i >=left ; i--)

}maxrightbordersum = 0;

rightbordersum = 0;

for ( i = center+1; i < right; i++)

}return (maxleftsum > maxrightsum ? maxleftsum : maxrightsum) > (maxleftbordersum + maxrightbordersum) ?

(maxleftsum > maxrightsum ? maxleftsum : maxrightsum) : (maxleftbordersum + maxrightbordersum);

}//演算法4:時間複雜度為o(n)

//聯機演算法,在任意時刻都能對他已經讀入的資料給出子串行問題的正確答案

int maxsubsequencesum4(int a, int n)

else

if (thissum < 0)

}return maxsum;

}

最大子串行和演算法

include stdio.h 演算法1 int maxsubsequencesum1 const int a,int n int thissum,maxsum,i,j,k maxsum 0 for i 0 i n i for j i j n j thissum 0 for k i k j k th...

最大子串行和演算法

題目 求a i 中和最大的子串行。時間複雜度o nlogn 使用分治 遞迴的方法。分別求出左邊n 2長度的最大子串行和 右邊n 2長度的最打字序列和 以及橫跨這兩部分且通過中間的最大和 要分別求出兩邊帶有最中間邊界的最子大序列和,將其相加 由於不是最簡單的方法,這裡不再贅述。時間複雜度o n 遍歷一...

演算法 最大子串行和

最大子串行和的問題,資料結構與演算法一書分析中給出了四種演算法,最優的演算法的時間複雜度為o n 1 定義控制台應用程式的入口點。2 34 include stdafx.h 5 include 6 using namespace std 7int maxsubsequesum const int a...