算法--最大子序列和

原理简析:从左到右,依次向右累加,只有当前的累加和(即max_now>=0)时候才能继续累加右边的,否则只能从右边的开始。但在往右边累加的过程中,右边的数可能是负数,所以添加一个最大累加和,并时时和当前的累加和做比较(即max_sum).

Python代码:

# -*- coding: utf-8 -*-
from random import randint
def max_subsequence_sum():
    #generate a unsorted list
    origin = []
    for i in xrange(0,10,1):
        origin.append(randint(-10,10))
    #最大连续子序列的和
    print origin
    max_sum = origin[0]
    max_now = origin[0]
    for i in xrange(0,len(origin),1):
        if max_now < 0:
            max_now = origin[i]
        else:
            max_now += origin[i]
        if max_now > max_sum:
            max_sum = max_now
    print max_sum

if __name__ == "__main__":
    max_subsequence_sum()

java 代码:

package blog.algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MaxSubsequnceSum {
    public static void main(String args[]){
        System.out.println("begin...");
        List<Integer> origin = new ArrayList<Integer>();
        int count = 10;
        Random rd = new Random();
        while(count > 0){
            int i = rd.nextInt(20);
            origin.add(i-10);
            count--;
            System.out.print("" + (i-10) + "  ");
        }
        System.out.println();
        int max_sum = origin.get(0);
        int max_now = origin.get(0);
        for(int i = 0,len = origin.size(); i < len; i++){
            if(max_now <=0){
                max_now = origin.get(i);
            }else{
                max_now += origin.get(i);
            }
            if(max_now > max_sum){
                max_sum = max_now;
                System.out.println("sum:" +max_sum);
            }
        }
        System.out.println(max_sum);
    }
}

jke_zq
50 声望2 粉丝