• MAXIMUM SUBSEQUENCE SUM PROBLEM


    排除不合理的项(负值), 设定一个标杆sum, 往后扫描看是否有比sum好的情况.

    We should ensure the following conditions:

      1. The result must be the max sum.

      2.* If more than one sum is max(same max value), choose the longer sequence.

      3.* If more than one sum is max & same length, choose the former sequence.

    #!/usr/bin/python2.7
    #File: maxChildSum.py
    #Author: lxw
    #Time: 2014-08-22
    #Usage: Find the max sum of a sub-sequence in a sequence.
    #NOTE:      @1: first, must be the max sum.
    #           @2: if more than one sum is max(same max value), choose the longer sequence.
    
    def main():
        #arr = [-12, 0, -14, -14, -13, -14, -2]  #"zero" test.
        #arr = [0, -14, -14, -13, -14, -2]  #another "zero" test.
        arr = [-100, -14, -14, -13, -14, -2]  #"all negtive" test.
        #arr = [-12, 10, 2, -14, -14, 13, -2]  #"longer sequence but not equal sum" test.
        #arr = [-12, 0, 10, -14, -14, -2]  #"as long as better" test.
        #arr = [-12, 0, 10, -14, -14, 3, 7, -2]  #"same sum & same length" test.
        #arr = [-12, 10, -14, -14, 3, 7, -2]  #"same sum but longer sequence" test.
    
        index = 0
        length = len(arr)
        while arr[index] < 0:
            index += 1
            if index == length:
                break
    
        if index < length:
            sum = -1    #This initial value is important.
            start = index
            temp_sum = 0    #sum
            temp_start = index
            end = 0
    
            while index < length:
                temp_sum += arr[index]
                if temp_sum >= 0:
                    if temp_sum > sum:
                        sum = temp_sum
                        start = temp_start
                        end = index
                    elif temp_sum == sum:
                        if start == temp_start:
                            end = index
                        elif index - temp_start > end - start:
                            start = temp_start
                            end = index
                else:
                    temp_sum = 0
                    temp_start = index + 1
                index += 1
            print "max sum:{0:<4}start:{1:<4}end:{2:<4}max length:{3:<4}".format(sum, start, end, end-start+1)
        else:
            #All the numbers are negative.
            print "max sum:{0:<4}start:{1:<4}end:{2:<4}max length:{3:<4}".format(0, 0, 0, 0)
    
    
    if __name__ == '__main__':
        main()
    else:
        print "Being imported as a module."
  • 相关阅读:
    DHT(Distributed Hash Table) Translator
    Introducing shard translator
    【转】shell脚本中echo显示内容带颜色
    javac 错误: 编码GBK的不可映射字符
    一致性哈希(consistent hashing)
    在bash shell中使用getfattr查看文件扩展属性
    css3在不同型号手机浏览器上的兼容一览表
    META是什么意思?
    JS异步加载的三种方式
    AJAX中的同步加载与异步加载
  • 原文地址:https://www.cnblogs.com/lxw0109/p/MAXIMUM-SUBSEQUENCE-SUM-PROBLEM.html
Copyright © 2020-2023  润新知