算法导论习题4-1-5 python解答
2016-12-03 00:57
363 查看
大半夜不睡觉做出来的题,一定不能浪费,记录下来,人真是老了,肯定有优化空间,但是现在不想想了,大家如果有优化的地方欢迎在评论留言,我一定改进。
#!/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 # 反之则将start到end的所有元素作为最大子数组 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)
相关文章推荐
- 算法导论2.3-7习题解答(合并排序算法及二分查找)
- 算法导论6.5-7习题解答
- 算法导论13-1节习题解答
- 算法导论第二章部分习题自我解答
- 《算法导论》第六章“堆排序”习题解答
- 《算法导论(第2版)》第20章习题解答
- 算法导论(3版)第5章少量习题的解答
- 算法导论10.2-7习题解答(单链表逆转)
- 算法导论10.1-7习题解答(用两个队列实现一个栈)
- 算法导论习题15.5-1解答
- 算法导论6.5-8习题解答(最小堆K路合并)
- 算法导论8-4习题解答
- 算法导论8-3(b)习题解答(trie树)
- 算法导论12.2节习题解答
- 算法导论9.3-9习题解答(寻找中位数)
- 算法导论2-2习题解答(冒泡算法)
- 算法导论8-3(a)习题解答(基数排序)
- 算法导论9.3-7习题解答
- 算法导论6.5-8习题解答(最小堆K路合并)
- 算法导论(3版)第4章习题的部分解答