/**
*
*求一串数字中的最大子序列
*/
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);
}
*
*求一串数字中的最大子序列
*/
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);
}