求一个数列中的最大子序列

/**
 * 
 *求一串数字中的最大子序列
 */
public class Demo1 {
public static void main(String[] args) {
int[] arr = {-1,-2,3,4,5,-5,4,-1};
seekMax3(arr);
}
/**
*找出数组中的最大子序列 算法一
*时间复杂度O(n^3)
*/
public static void seekMax(int[] arr){
int maxSum = 0;
for(int i=0;i<arr.length;i++){//子序列的最左端
for(int j=i;j<arr.length;j++){//子序列的最右段
//计算子序列的和
int tempSum = 0;
for(int k=i;k<=j;k++){
tempSum+=arr[k];
}
if(tempSum>maxSum){
maxSum = tempSum;
}
}
}
System.out.println(maxSum);
}
/**
*找出数组中的最大子序列 算法二
*时间复杂度 O(n^2)
*/
public static void seekMax2(int[] arr){
int maxSum = 0;
for(int i=0;i<arr.length;i++){//子序列的最左端
int tempSum = 0;
for(int j=i;j<arr.length;j++){//子序列的最右段
tempSum+=arr[j];
if(tempSum>maxSum){
maxSum = tempSum;
}
}
}
System.out.println(maxSum);
}
/**
* 在线算法
* 时间复杂度O(n)
*/
public static void seekMax3(int[] arr){
int maxSum = 0;
int tempSUm = 0;
for(int i=0;i<arr.length;i++){
tempSUm+=arr[i];
if(tempSUm>maxSum){
maxSum = tempSUm;
}
if(tempSUm<0){
tempSUm = 0;
}
}
System.out.println(maxSum);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值