算法导论习题4-1-5 python解答

大半夜不睡觉做出来的题,一定不能浪费,记录下来,人真是老了,肯定有优化空间,但是现在不想想了,大家如果有优化的地方欢迎在评论留言,我一定改进。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
input = [13,-3,-25,20,-3,-16,-18,18,20,-7,12,-5,-22,15,-4,7]

def fast(input):
    # 记录最大的子数组的和
    max = 0
    # 记录除了最大子数组的右脚标到i所在位置的数字和
    temp = 0
    # 记录temp中的到当前脚标i所在位置的最大子数组
    other_temp = 0
    # 记录other_temp的左脚标
    start_tmp = 1
    # 记录最大子数组的左脚标
    start = 0
    # 记录最大子数组的右脚标
    end = 0
    i = 0
    while i < len(input):
        if input[i] > 0:
            # 如果当前位置元素大于max,则直接从当前位置开始
            if input[i] > max:
                max = input[i]
                start = i
                end = i
                temp = 0
                other_temp = 0
            elif input[i] + temp > 0:
                # 如果当前元素加上中间所有临时元素再加上当前最大子数组和小于当前元素加上临时元素的最大子数组,则抛弃max而使用other_temp
                if input[i] + temp + max < input[i] + other_temp:
                    max = other_temp + input[i]
                    start = start_tmp
                # 反之则将startend的所有元素作为最大子数组
                else:
                    max = max + temp + input[i]
                temp = 0
                other_temp = 0
                end = i
            else:
                temp = temp + input[i]
                other_temp = other_temp + input[i]
                # 如果临时数组中的最大子数组已经大于max,则使用other_temp
                if other_temp > max:
                    max = other_temp
                    start = start_tmp
                    temp = 0
                    other_temp = 0

        else:
            temp = temp + input[i]
            other_temp = other_temp + input[i]
            # 如果temp+max已经小于0且当前元素<0,则临时数组没有意义,临时数组的脚标至少要从下个元素开始才有意义
            if temp + max < 0:
                other_temp = 0
                start_tmp = i+1
        i = i+1

    print(max, start, end)
    # 输出(43, 7, 10

猜你喜欢

转载自blog.csdn.net/cckooo/article/details/53440913