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

本文介绍了一种寻找数组中最大子数组和的方法,并通过具体示例进行了解释。作者分享了其深夜完成的代码实现,旨在帮助读者理解并优化算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#!/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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值