java实现最大子序列问题——————性能最优的算法

来源:互联网 发布:鸭鸭网络数字点卡平台 编辑:程序博客网 时间:2024/06/05 08:29
 问题:求一维数组中连续子向量的最大和。

       例如:{3,4,-2,-9,-10,8,-1,22}则最大连续子向量的和 为 8+(-1)+22=29

 

package xiancheng;

/**
 *
 * @author Administrator zyyjiao@mail.ustc.edu.cn
 */
public class Scan {

    public static void main(String[] args) {
        int a[] = {3, 4, -2, -9, -10, 8, -1, 22};
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
            if (sum < 0) {
                sum = 0;
            }
        }

        System.out.println("max=" + sum);


    }
}

 

原创粉丝点击