最大子序列和的四种算法

        
          

一 穷举法
public int getMax(int[] a) {
int maxSum = 0, sum;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
sum = 0;
for (int k = i; k < j; k++) {
sum += a[k];
}
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
时间复杂度为:O(N^3)

二 穷举法改进
public int getMax(int[] a) {
int maxSum = 0, sum;
for (int i = 0; i < a.length; i++) {
sum = 0;
for (int j = i; j < a.length; j++) {
sum += a[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
时间复杂度为:O(N^2)

三 分而治之法
public int getMax(int[] a, int left, int right) {
if (left == right) {
return a[left] > 0 ? a[left] : 0;
}
int center = (left + right) / 2;
int maxLeftSum = getMax(a, left, center);
int maxRightSum = getMax(a, center + 1, right);

int maxLeftBorderSum = 0, leftSum = 0;
for (int i = center; i >= left; i--) {
leftSum += a[i];
if (leftSum > maxLeftBorderSum) {
maxLeftBorderSum = leftSum;
}
}

int maxRightBorderSum = 0, rightSum = 0;
for (int i = center + 1; i <= right; i++) {
rightSum += a[i];
if (rightSum > maxRightBorderSum) {
maxRightBorderSum = rightSum;
}
}

return max(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);
}
private int max(int x, int y, int z) {
return x > y ? (x > z ? x : z) : (y > z ? y : z);
}
时间复杂度为:O(Nlog(N))



四 最优起点法
public int getMax(int[] a) {
int maxSum = 0, sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (sum > maxSum) {
maxSum = sum;
} else if (sum < 0) {
sum = 0;
}
}
return maxSum;
}
时间复杂度为:O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值